首页 > 解决方案 > MongoDB 聚合查找不适用于 localfield _id

问题描述

这是我的内容Schema-

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ContentSchema = new Schema({
    linkName: {
        type: String,

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

和内容评论Schema——

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const contentCommentSchema = new Schema({
    text: {
        type: String,

    },
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    content: {
        type: Schema.Types.ObjectId,
        ref: 'Content'
    }
},
{
    timestamps: true

});
module.exports = mongoose.model('contentComment', contentCommentSchema);

当我尝试$lookup从 contentComment 中返回时,它每次都返回 0 条记录。但是在 db 中为相应的内容创建了注释。这是Aggregation-

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

我在那里缺少什么吗?

标签: mongodblookupaggregationmongoose-schema

解决方案


推荐阅读