我有一个带有数组 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 许可协议
我找到了答案:
populate('lists.list')
有效。感谢这个问题: Mongoose populate within an object?