Mongoose – 子模式引用父子文档
是否有可能有一个类似于以下的mongoose纲要:
var categorySchema = new Schema({ name : String }); var childSchema = new Schema({ name : String, category : { type : Schema.Types.ObjectId, ref : 'parent.categories' } }); var parentSchema = new Schema({ categories : [categorySchema], children : [childSchema] });
基本上,一个孩子只能有一个父类包含的类别。 我正在尝试做什么? 如果不是最干净的方式做到这一点?
如果在categorySchema
只有一个字段name
,也许你可以把它parentSchema
没有population
parentSchema
中,
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
文档时的逻辑相同。