I have the following Mongoose schema as defined on this page
const AuthorSchema = new Schema({
name: String
});
const BlogPostSchema = new Schema({
title: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' },
comments: [{
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' },
content: String
}]
});
Now I want to create a virtual on AuthorSchema to get the BlogPosts which have comments of that author.
I tried creating a virtual function but with no success
Both virtual
and methods
can solve your problems:
Virtual:
// Model
AuthorSchema.virtual('blogPosts').get(function () {
return this.model('BlogPost').find({
comments: { $elemMatch: { author: this._id } },
})
});
// Usage
const author = await Author.findById(id);
const blogPosts = await author.blogPosts;
Methods:
// Model
AuthorSchema.method.blogPosts= function (cb) {
return this.model('BlogPost').find({
comments: { $elemMatch: { author: this._id } },
}, cb)
};
// Usage
const author = await Author.findById(id);
const blogPosts = await author.blogPosts();