MongoDB 聚合查找不适用于发布评论

时间:2021-01-21 13:02:59

标签: mongodb mongoose lookup aggregation

我有两个集合需要在聚合中查找。帖子需要在列表中查找评论非常简单。

这里我定义了 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 的空数组。

以下是 contentsMongoDB Compass 的两个屏幕截图 -

content documents

contentComments -

content comments documents

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

empty result for nbComments

1 个答案:

答案 0 :(得分:1)

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"
        }
        .......
    }
]; 
相关问题