是否可能有类似于以下内容的“猫鼬模式”:
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]
});基本上,子类只能包含其父类所包含的类别。我想做的事有可能吗?如果不是的话,最干净的方法是什么呢?
发布于 2016-02-29 05:06:38
如果categorySchema中只有一个字段categorySchema,也许您可以将其放入parentSchema而不使用population,如下所示,
var childSchema = new Schema({
name : String,
category : {
name: String
}
});
var parentSchema = new Schema({
categories : [{name: String}],
children : [childSchema]
});当尝试将新的child插入到parent中时,您可以先查询parent,然后迭代categories以获得现有的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文档时,也会使用相同的逻辑。
https://stackoverflow.com/questions/35690897
复制相似问题