【问题标题】:How do I get a virtual in mongoose, If a property is deselected如果取消选择属性,如何在猫鼬中获得虚拟
【发布时间】:2021-09-12 18:10:29
【问题描述】:

假设我发布了模型,并且架构包含 UserIdTitleDesclikes 数组userId 为 ref

当我进行查询时,我会得到一个像这样的虚拟属性来找出帖子的数量

schema.virtual("numLikes").get(function () {
  return this.likes.length;
});

但问题是当我运行 findById() 方法时,我不想从数据库中获取喜欢,因为喜欢数组将包含大量用户

 const post = await Post.findById(postId).select("-likes -shares");

那么如何在不获取点赞数组的情况下获得点赞数?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    我相信这可以通过聚合来完成,通过在投影中使用 $size 运算符:

    const aggregate = Post.aggregate([
      { $match: {_id: postId}},
      { $project: {
          numberOfLikes: { $size: "$likes" }
        }
      }
    ]);
    

    https://docs.mongodb.com/manual/reference/operator/aggregation/size/ https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-project

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2018-12-23
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多