Question

I am new to Node+Mongoose, and am currently in the process of creating an API using KeystoneJS. I've managed to populate all posts with the author's email and name. My question is, is there a way to populate the post with author everytime, possibly with some middlewear, without having to rewrite it in each method where I retrieve posts? My goal is to not have multiple instances of populate('author', 'email name') scattered throughout the code. For instance, in the future, I'd like to include the author's profile photo url as well, and I'd prefer to be able to make that change in a single place, that will then be reflected in every place that I retrieve posts.

Current implementation:

Post.model.find().populate('author', 'email name').exec(function (err, posts) {
    if (!err) {
        return res.json(posts);
    } else {
        return res.status(500).send("Error:<br><br>" + JSON.stringify(err));
    }
});

Post.model.findById(req.params.id).populate('author', 'email name').exec(function (err, post) {
    if(!err) {
        if (post) {
            return res.json(post);
        } else {
            return res.json({ error: 'Not found' });
        }
    } else {
        return res.status(500).send("Error:<br><br>" + JSON.stringify(err));
    }
});
Was it helpful?

Solution

You can create model using statics. This is example of methods for schema

PostSchema.statics = {
getAll: function(cb) {
    return this
        .find()
        .populate('author', 'email name')
        .exec(cb);
}
}

You still should use "populate", but it will be in schema file, so you will not care about it in future

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top