如何返回子文档猫鼬的计数数组

时间:2021-07-20 18:56:23

标签: node.js express mongoose

我想从 Place 模型中获取评论总数,但我找不到获取它的方法,因为我不想用 GET /places 填充评论。

这是我的地方模型

 const placeSchema = mongoose.Schema(
  {
    type: { type: String },
    english: { type: String },
    province_code: { type: String },
    district_code: { type: String, required: true },
    commune_code: { type: String },
    village_code: { type: String },
    lat: { type: Number },
    lon: { type: Number },
    body: { type: String },
    images: [{ type: String }],
    comments: [{ type: mongoose.Types.ObjectId, ref: Comment }],
  },
  {
    timestamps: {
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    },
  }
)

我使用这个查询

data = await Place
          .find()
          .limit(5)
          .skip(0)
          .populate('comments')
          .exec()

我想得到这样的回应

 {
    "data": [
        {
            "images": [],
            "comments": 6,
            "type": "place",
            "english": "99Boko",
            "province_code": "23",
            "district_code": "2302",
            "commune_code": "230202",
            "village_code": "23020202",
            "lat": 135.2039,
            "lon": 104.01734762756038,
            "body": "<b>This place is really good</b>",
            "created_at": "2021-07-20T17:41:52.202Z",
            "updated_at": "2021-07-20T17:41:52.202Z",
            "id": "60f70ae08e54941530d14c4c"
        },
]}

有人知道获得这种响应的解决方案吗?

1 个答案:

答案 0 :(得分:1)

我发现获取评论长度是使用虚拟计数

placeSchema.virtual('comment_length', {
  ref: Comment, // model to use for matching
  localField: 'comments', // from `localField` i.e., Place
  foreignField: '_id', // is equal to `foreignField` of Comment schema
  count: true, //only get the number of docs
})

placeSchema.set('toObject', { virtuals: true })
placeSchema.set('toJSON', { virtuals: true })

并使用此查询

 data = await Place
            .find().populate({ path: 'comment_length', count: true })
            .exec()