Skip to content

Instantly share code, notes, and snippets.

@wilsonpage
Created May 4, 2012 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilsonpage/2593159 to your computer and use it in GitHub Desktop.
Save wilsonpage/2593159 to your computer and use it in GitHub Desktop.
How to populate model ref property after instantiation?
var commentsSchema = new Schema({
content: { type: String },
_user: { type: Schema.ObjectId, ref: 'users' },
});
//...
// Get a comment without populating
CommentsModel
.findOne({ _id: COMMENT_ID }, function(err, comment) {
UsersModel
.findOne({ _id: comment._user }, function(err, user) {
// Attempt to set user model on comment (like .populate)
comment.set('_user', user);
console.log(comment);
//=> comment._user is still just the original object id.
// .set() command seems to have been ignored by Mongoose.
})
});
@wilsonpage
Copy link
Author

If the comment._user was not populated on the original find, what is the best method to mimic populate()? How can I force mongoose to set the user model on the comment._user property? I think it's something to do with types, not sure how to work round it though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment