簡體   English   中英

Mongoose 查詢 Object 數組或 Object 數組的虛擬

[英]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 但沒有成功

virtualmethods都可以解決你的問題:

虛擬的:

// 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM