虚拟种群在猫鼬中不起作用

时间:2021-07-09 21:05:42

标签: node.js database mongodb mongoose populate

在我的项目中,我有单独的猫鼬模型用于帖子和评论;我希望虚拟填充帖子中的评论。为此,我在评论模型中有一个字段“forPost”

这是评论模型

const commentSchema = new mongoose.Schema({
    text: {
        type: String, 
        required: [true, 'A comment cannot be empty']
    },
    byUser: {
        type: mongoose.Schema.ObjectId,
        ref: 'User',
        required: [true, 'A comment must have a user']
    }, 
    forPost: {
        type: mongoose.Schema.ObjectId,
        ref: 'Post',
        required: [true, 'A comment must belong to some post']
    },
    createdAt: {
        type: Date,
        default: Date.now()
    }
})

我正在尝试使用猫鼬的虚拟填充在帖子中填充评论

const postSchema = new mongoose.Schema({
    title : {
        type: String, 
        required: [true, 'A post must have a title']
    },
    imageUrl : String,
    content: {
        type: String,
        required: [true, 'A post must have some content']
    },
    upvotes: {
        type: Number,
        default: 0
    },
    downvotes: {
        type: Number,
        default: 0
    },
    byUser: {
        type: mongoose.Schema.ObjectId,
        ref: 'User',
        required: [true, 'A post must have an owner']
    },
    forServer: String
}, {
    toJSON: {
        virtuals: true
    },
    toObject: {
        virtuals: true
    }
})

postSchema.virtual('comments', {
    ref: 'Comment',
    foreignField: 'forPost',
    localField: '_id'
})

但是,评论没有被填充,当我使用 GET 请求获取帖子时我看不到它们

为什么会这样以及如何解决这个问题

0 个答案:

没有答案