I don't understand the problem when i read http://mongoosejs.com/docs/populate.html. I don't fully understand what the populate
function does. I picked it up from meanjs
sample source code:
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}});
Thanks in advance.
In Article
document, you are storing userId of the users.
Now while querying Article
document, with articles you want to get users for each then you can use populate.
Now when you access articles[index].user
, then it will return object instead of ObjectId
value (_id
property of user).
Second argument defines that which field should be retrieved in User
object. Here it is displayName
. So it will retrieve _id
and displayName
of User
. If you want to exclude _id you can specify "-_id displayName"