To populate a sub-document in Node Mongoose after creating it, we call the populate
method.
For instance, we write
Item.find({})
.populate("comments.created_by")
.exec((err, items) => {
console.log(items[0].comments[0].created_by.name);
});
to call find
to get the items from Items
.
And we call populate
to get the data for the comments.created_by
field for each entry.
Then we call exec
to return the results as a plain array.
We get the results from the items
array.