首页 > 解决方案 > 获取属性猫鼬的数组长度

问题描述

在我的情况下,我需要属性“idsProfil”中的 id 数量。我不希望属性中的所有 id ,只是数字。

这就是我获得出版物的方式。

    const publication = await this.publicationService.paginated(
      {
        $and: [
          { deletedAt: null },
        ],
        $or: [
          { profile: friends},
          { profile: req.user.profile},
        ]
      },
      {populate: [
        ['profile'],
        ['like'],
      ]},
      req.query)

这就是我的对象的创建方式。

const LikeSchema = new Schema({
  _id: String,
  idsProfil: {
    type: [String],
  }
})

我不能使用像月光一样的预验证,因为我使用 FindAndUpdate,我不能使用 Save()

标签: node.jsmongodb

解决方案


要使用 Mongoose 获取集合中存在的文档数量,您可以使用Model.estimatedDocumentCount()。它将使用元数据浏览您的收藏。
另一种方法是使用Model.countDocuments()。但是,由于它浏览集合的方式,此功能在大型集合上效率不高。它正在扫描整个集合并计算每个文档,效率不高。


推荐阅读