[英]Mongoose Querying on Array of Object or Virtual for array of Object
我有此頁面上定義的以下 Mongoose 架構
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
}]
});
現在我想在 AuthorSchema 上創建一個虛擬的,以獲取具有該作者評論的 BlogPosts。
我嘗試創建一個虛擬 function 但沒有成功
virtual
和methods
都可以解決你的問題:
虛擬的:
// 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;
方法:
// 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.