mongoosejs populate code example
Example 1: mongoose populate filter
Story.
find(...).
populate({
path: 'fans',
match: { age: { $gte: 21 } },
select: 'name -_id'
}).
exec();
Example 2: mongoose create populate response
let user = await User.create({ ... })
user = await user.populate('company').execPopulate()
Example 3: mongodb populate document
Story.
findOne({ title: 'Casino Royale' }).
populate('author').
exec(function (err, story) {
if (err) return handleError(err);
console.log('The author is %s', story.author.name);
});
Example 4: mongoos populate a ref
const storySchema = Schema({
authors: [{ type: Schema.Types.ObjectId, ref: 'Person' }],
title: String
});
const story = await Story.findOne({ title: 'Casino Royale' }).populate('authors');
story.authors;