Saving populated values in Mongoose Saving populated values in Mongoose mongoose mongoose

Saving populated values in Mongoose


Instead of using depopulate() method of mongoose, you can use underscore library of node, which provides a function pick and returns the opted values from given object and computes result faster here is example!

app.get('/post/:id', function (req, res, next) {Post.findById(req.params.id).populate('likes').exec(function (err, post) {if (err) return next(err); var depopulate  = _.pick(post, '_id'); res.json(depopulate);});});

depopulate variable will store _id's from resulted queried document and you can easily send all _id's to client.


I know this question was posted 2 years ago, but i thought that it might help you..You can override some pre-defined methods to get done what you need.

UserSchema.methods.toJSON = function () {    var user = this.toObject();      return _.pick(user, ['_id', 'email']);};

Like i have overridden toJSON method to send only _id and email instead of sending whole user doc back.