我有一个Mongoose模式,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);
Run Code Online (Sandbox Code Playgroud)
但是,如果没有得到,我就无法populate按预期工作TypeError: Cannot read property 'ref' of undefined.我试过了populate('list'),populate('lists list')但我要么没有正确调用,要么我的架构没有正确形成.如果我只是自己引用列表,我就没有这个问题:
lists: [
{
type: Schema.ObjectId,
require: true,
ref: "List"
}
]
Run Code Online (Sandbox Code Playgroud)
但我希望在每个列表旁边都有分配数组.我需要做什么才能获得我想要的行为?
nev*_*fox 93
我找到了答案:populate('lists.list')有效.感谢这个问题:Mongoose填充在一个对象中?
实际答案:
用这个,
populate('lists.list')
Run Code Online (Sandbox Code Playgroud)
额外的:
这里的列表是对象数组(列表)。在 JS 中你可以这样访问它,
console.log(lists.list);
Run Code Online (Sandbox Code Playgroud)
而且MongoDB语法和JS语法有99%相似。所以....................
小智 5
lists: [
{
list: {
type: Schema.ObjectId,
require: true,
ref: "List"
},
allocations: [
{
type: Number,
required: true
}
]
}
],
Run Code Online (Sandbox Code Playgroud)
=> 因为它是一个对象数组,你可以这样做 -: Portfolio.populate('lists.list');
2.
lists: [
{
type: Schema.ObjectId,
require: true,
ref: "List"
}
]
Run Code Online (Sandbox Code Playgroud)
=> 因为它是一个数组,所以你只需要这样做 -: Portfolio.populate('lists');
| 归档时间: |
|
| 查看次数: |
61010 次 |
| 最近记录: |