在这种情况下,我需要分配多个多对一关系,如下所示:
var portfolioSchema = new Schema({
volatility : Number,
bonds : {
percentage : { type: Number, default: 0.6 },
USA : {
percentage : { type: Number, default: 0.7 },
treasury : {
percentage : { type: Number, default: 0.4 },
securities : [ { type: ObjectId, ref: 'Security' } ]
},
municipal : {
percentage : { type: Number, default: 0.2 },
securities : [ { type: ObjectId, ref: 'Security' } ]
},
corporate : {
percentage : { type: Number, default: 0.4 },
securities : [ { type: ObjectId, ref: 'Security' } ]
}
},
international : {
percentage : { type: Number, default: 0.3 },
developed : {
percentage : { type: Number, default: 0.7 },
securities : [ { type: ObjectId, ref: 'Security' } ]
},
emergent : {
percentage : { type: Number, default: 0.3 },
securities : [ { type: ObjectId, ref: 'Security' } ]
}
}
},
stocks : {
percentage : { type: Number, default: 0.4 },
USA : {
percentage : { type: Number, default: 0.7 },
largeCaps : {
percentage : { type: Number, default: 0.4 },
securities : [ { type: ObjectId, ref: 'Security' } ]
},
mediumCaps : {
percentage : { type: Number, default: 0.4 },
securities : [ { type: ObjectId, ref: 'Security' } ]
},
smallCaps : {
percentage : { type: Number, default: 0.2 },
securities : [ { type: ObjectId, ref: 'Security' } ]
}
},
international : {
percentage : { type: Number, default: 0.3 },
developed : {
percentage : { type: Number, default: 0.7 },
securities : [ { type: ObjectId, ref: 'Security' } ]
},
emergent : {
percentage : { type: Number, default: 0.3 },
securities : [ { type: ObjectId, ref: 'Security' } ]
}
}
},
_goal : { type: ObjectId, ref: 'Goal' }
});
var securitySchema = new Schema({
name : { type: Date, required: true },
avgReturn : Number,
avgRisk : Number,
percentage : Number
});
但是,在我看来,仅使用Array
数据类型而不是[ { type: ObjectId, ref: 'Security' } ]
会更容易。
我不确定应该怎么做。有人会知道这样做的适当方法吗?谢谢!
答案 0 :(得分:1)
如果您的数组仅由Security
个对象组成,则应使用[ { type: ObjectId, ref: 'Security' } ]
。
答案 1 :(得分:0)
你不应该在mongoose模式中写下Array
这个词。这是一个相关的答案。
How to define object in array in Mongoose schema correctly with 2d geo index
因此,对您的问题的简短回答是:使用[ { type: ObjectId, ref: 'Security' } ]
。