mongoose populate virtuals

Solutions on MaxInterview for mongoose populate virtuals by the best coders in the world

showing results for - "mongoose populate virtuals"
Alessandro
28 Feb 2016
1const userSchema = mongoose.Schema({ _id: Number, email: String });
2const blogPostSchema = mongoose.Schema({
3  title: String,
4  authorId: Number
5});
6// When you `populate()` the `author` virtual, Mongoose will find the
7// first document in the User model whose `_id` matches this document's
8// `authorId` property.
9blogPostSchema.virtual('author', {
10  ref: 'User',
11  localField: 'authorId',
12  foreignField: '_id',
13  justOne: true
14});
15const User = mongoose.model('User', userSchema);
16const BlogPost = mongoose.model('BlogPost', blogPostSchema);
17await BlogPost.create({ title: 'Introduction to Mongoose', authorId: 1 });
18await User.create({ _id: 1, email: 'test@gmail.com' });
19
20const doc = await BlogPost.findOne().populate('author');
21doc.author.email; // 'test@gmail.com'