【问题标题】:Mongoose Populate Virtual Option Count returns whole document's countMongoose 填充虚拟选项计数返回整个文档的计数
【发布时间】:2019-06-28 05:59:47
【问题描述】:

mongoose 填充虚拟计数应该返回满足 ref、localField 和 foreignField 的文档总数。但是当我使用它时,它会返回忽略 ref、localField 和 foreignField 的文档总数。

我在没有 count 选项的情况下使用它,它正确地返回了满足 ref、localField 和 foreignField 的文档数。 但是当我包含计数时,它会返回忽略它们的文档总数。

AuthorSchema.virtual('books', {
  ref: 'books',
  localField: '_id',
  foreignField: 'author_id'
});

返回 书数:[ { 名称:“狐狸的梦想”, 日期:“2019-01-13T00:44:22.564Z” } ]

但是

AuthorSchema.virtual('books_count', {
 ref: 'books',
 localField: '_id',
 foreignField: 'author_id'
});

返回 4,即收藏的图书总数

但我期待 1,因为 1 满足 ref、localField 和 foreignField

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    根据猫鼬的文档(参考https://mongoosejs.com/docs/populate.html#count) 您应该将 count: true 添加到选项中,这会使您的代码如下所示:

    AuthorSchema.virtual('books', {
      ref: 'books',
      localField: '_id',
      foreignField: 'author_id',
      count: true
    });
    

    【讨论】:

      猜你喜欢
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 2020-12-05
      • 2014-11-20
      • 2013-06-30
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多