如果categorySchema中只有一个字段name,也许你可以把它放在parentSchema中而不用population,如下所示,
var childSchema = new Schema({
name : String,
category : {
name: String
}
});
var parentSchema = new Schema({
categories : [{name: String}],
children : [childSchema]
});
当尝试将新的child插入parent时,您可以先查询parent,然后迭代categories以获取现有的并将其添加到children,最后保存parent,示例代码如下
Parent.find({_id: parent._id})
.exec(function(err, p) {
if (err) throw err;
var p = new Child({name: 'tt'});
p.categories.forEach(function(c) {
if (c /*find the match one*/) {
p.category = c; // assign the existing category to children
}
});
// save this parent
p.save(function(err) {...});
});
如果categorySchema 中有很多字段,也许将其定义为单独的架构可能是一种选择,以防Parent 中有很多类别而使父集合太大。
var categorySchema = new Schema({
name : String,
// other fields....
});
var Category = mongoose.model('Category', categorySchema);
var childSchema = new Schema({
name : String,
category : {type : Schema.Types.ObjectId, ref : 'Category'}
});
var parentSchema = new Schema({
categories : [{type : Schema.Types.ObjectId, ref : 'Category'}],
children : [childSchema]
});
尝试将新的children 添加到parent 文档时的逻辑与上述相同。