在架构中包括子文档的数量

时间:2019-07-02 14:46:21

标签: node.js mongoose

在我的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是具有标题和描述的架构。点赞是跟踪特定帖子点赞次数的模式。因此它只有postID。

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

有没有简单的方法可以实现它?

1 个答案:

答案 0 :(得分:0)

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

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