【问题标题】:Include count of subdocuments in schema在架构中包含子文档的计数
【发布时间】:2019-07-08 18:06:35
【问题描述】:

在我的 NodeJS 项目中,我正在创建 Mongoose 模式,如下所示:

//Likes Schema
var likesSchema = mongoose.Schema({
  postId: { type: mongoose.Schema.Types.ObjectId, ref: "Post", required: 'Provide the news ID to which this comment belongs' },
});
module.exports = mongoose.model('Likes', likesSchema);

//Post schema
var postSchema = mongoose.Schema({
  title: { type: String, required: 'Kindly enter the title' },
  description: { type: String, required: 'Kindly enter the description of the news' }
});
module.exports = mongoose.model('Post', postSchema);

Post 是一个有标题和描述的模式。 Like 是一种模式,用于跟踪特定帖子的点赞数。所以它只有postID。

现在我想将喜欢的“计数”作为变量包含在“发布”模式中。我不想在查询执行期间计算喜欢。

有什么简单的方法可以实现吗?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    经过反复试验,我找到了解决方案:

    db.Post.aggregate([
        {
            $lookup: {
                from: "Likes",
                localField:"_id",
                foreignField: "postId",
                as: "likes"
            }
        },
        {
            $project: {
                title: 1,
                description: 1,
                count: { $size: "$likes" }
            }
        }
    ]).pretty()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-26
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      相关资源
      最近更新 更多