首页 > 解决方案 > MongoDB 聚合查找不适用于帖子评论

问题描述

我有两个需要在聚合上查找的集合。在帖子需要查找关于列表的评论时,这非常简单。

在这里我定义Content了模式 -

const ContentSchema = new Schema({
    .........
    linkName: {
        type: String,

    },
    description: {
        type: String,
    }
},
{
    timestamps: true 
});
module.exports = mongoose.model('Content', ContentSchema);

评论架构contentComment-

const contentCommentSchema = new Schema({
    ........
    content: {
        type: Schema.Types.ObjectId,
        ref: 'Content'
    }
},
{
    timestamps: true
});
module.exports = mongoose.model('contentComment', contentCommentSchema);

这是我试图列出Content带有相应评论的帖子(架构)的查询contentComment-

const contentPromise = Content.aggregate([
    {
        $lookup: {
            from: 'contentComments',
            let: { contentId: '$_id' },
            pipeline: [{
                $match: {
                    $expr: {
                        $eq: [ '$content', '$$contentId' ]
                    }
                } 
            }],
            as: 'nbComments'
        }
        .......
    }
]);

我也试过以下$lookup-

const contentPromise = Content.aggregate([
    {
        $lookup: {
            from: "contentComments",
            localField: "_id",
            foreignField: "content",
            as: "nbComments"
        }
        .......
    }
];

但每次它返回空数组comments

这是MongoDB Compass的两个屏幕截图,用于contents-

内容文件

contentComments-

内容评论文件

nbComments即使对特定帖子/内容有足够的评论,我也无法弄清楚返回空错误的问题。这是一个屏幕截图 -

nbComments 的空结果

标签: mongodbmongooselookupaggregation

解决方案


from 使用复数小写集合名称,就像您在 mongo 终端中使用的那样。

所以你必须使用 contentcomments 而不是 contentComments

您可以使用 contentComment.collection.name

例子:

const AwesomeNameSchema = new Schema({
=   
});
module.exports = mongoose.model('AwesomeName', AwesomeNameSchema);

在 mongo 终端

db.AwesomeName.count(); // return 0, not working
db.AwesomeNames.count(); // return 0, not working
db.awesomename.count(); // return 0, not working

db.awesomenames.count(); // return X, working solution

在猫鼬查找中

var AwesomeName = require("./models/AwesomeName.js");
var ParentAwesomeName = require("./models/ParentAwesomeName.js");

// not working
ParentAwesomeName.aggregate([
    {
        $lookup: {
            from: "AwesomeNames",
            localField: "_id",
            foreignField: "awesome_name",
            as: "awesome"
        }
        .......
    }
]; 

// working
ParentAwesomeName.aggregate([
    {
        $lookup: {
            from: "awesomenames",
            localField: "_id",
            foreignField: "awesome_name",
            as: "awesome"
        }
        .......
    }
]; 

// working
ParentAwesomeName.aggregate([
    {
        $lookup: {
            from: AwesomeName.collection.name,
            localField: "_id",
            foreignField: "awesome_name",
            as: "awesome"
        }
        .......
    }
]; 

推荐阅读