Mongoose 填充包含 ref 的对象数组

2024-02-26

我有一个带有数组的猫鼬模式lists由对另一个集合的引用和嵌套的数字数组组成的对象:

var Schema, exports, mongoose, schema;
    
mongoose = require("mongoose");
    
Schema = mongoose.Schema;
    
schema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    lists: [{
        list: {
            type: Schema.ObjectId,
            require: true,
            ref: "List"
        },
        allocations: [{
            type: Number,
            required: true
        }]
    }],
    createdAt: {
        type: Date,
        "default": Date.now
    },
    updatedAt: {
        type: Date
    }
});
    
exports = module.exports = mongoose.model("Portfolio", schema);

但是,我无法得到populate按预期工作而无需获得TypeError: Cannot read property 'ref' of undefined。我试过了populate('list') and populate('lists list')但我要么没有正确调用事物,要么我的架构没有正确形成。如果我简单地引用列表本身,我就不会遇到这个问题:

lists: [{
    type: Schema.ObjectId,
    require: true,
    ref: "List"
}]

但我希望每个列表旁边都有分配数组。我需要做什么才能获得我想要的行为?


我找到了答案:populate('lists.list')作品。感谢这个问题:猫鼬填充在一个对象内? https://stackoverflow.com/questions/14594511/mongoose-populate-within-an-object?rq=1

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongoose 填充包含 ref 的对象数组 的相关文章

随机推荐