5 min read
•Question 16 of 27mediumHow does populate work in Mongoose?
Understanding document references.
What You'll Learn
- Setting up references
- Using populate
- Deep population
Define References
code.jsJavaScript
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
const Post = mongoose.model('Post', postSchema);Basic Populate
code.jsJavaScript
// Populate single field
const post = await Post.findById(id).populate('author');
// Result: { ..., author: { _id: ..., name: 'John', email: '...' } }
// Populate multiple fields
const post = await Post.findById(id)
.populate('author')
.populate('comments');
// Or
const post = await Post.findById(id).populate('author comments');Select Fields
code.jsJavaScript
const post = await Post.findById(id)
.populate('author', 'name email') // Only name and email
.populate('comments', '-__v'); // Exclude __vPopulate with Options
code.jsJavaScript
const post = await Post.findById(id).populate({
path: 'comments',
match: { approved: true },
select: 'text createdAt',
options: { sort: { createdAt: -1 }, limit: 5 }
});Deep Populate
code.jsJavaScript
// Comment has author reference
const post = await Post.findById(id).populate({
path: 'comments',
populate: { path: 'author', select: 'name' }
});Virtual Populate
code.jsJavaScript
userSchema.virtual('posts', {
ref: 'Post',
localField: '_id',
foreignField: 'author'
});
const user = await User.findById(id).populate('posts');