猫鼬填充包含 ref 的对象数组

新手上路,请多包涵

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

 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')populate('lists list') 但我要么没有正确调用,要么我的架构没有正确形成。如果我自己简单地引用列表,我就没有这个问题:

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

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

原文由 neverfox 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 364
2 个回答

实际答案:

用这个,

 populate('lists.list')

额外的:

这里的列表是一个对象数组(列表)。在 JS 中你可以这样访问它,

 console.log(lists.list);

MongoDB语法与JS语法99%相似。所以………………..

原文由 Rohit Nishad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏