MongoDB 聚合查找不适用于 post 评论

MongoDB aggregate lookup not working for post comments

我有两个集合需要查找 aggregate.That 非常简单,帖子需要查找列表中的评论。

这里我定义了Content schema -

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"
        }
        .......
    }
];

但每次 returns comments 的空数组。

这是 MongoDB Compass for contents -

的两张截图

contentComments-

我无法解决为 nbComments 返回空错误的问题,即使对特定的 post/content 有足够的评论。这是屏幕截图 -

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

在 mongoose 查找中

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"
        }
        .......
    }
];