0

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

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.