如何填充嵌套的Mongooseembedded式文档

我已经阅读并重新阅读了关于Mongoose中embedded和链接文档的几篇文章。 根据我所阅读的内容,我得出结论,最好是具有类似于以下的模式结构:

var CategoriesSchema = new Schema({ year : {type: Number, index: true}, make : {type: String, index: true}, model : {type: String, index: true}, body : {type: String, index: true} }); var ColorsSchema = new Schema({ name : String, id : String, surcharge : Number }); var MaterialsSchema = new Schema({ name : {type: String, index: true}, surcharge : String, colors : [ColorsSchema] }); var StyleSchema = new Schema({ name : {type: String, index: true}, surcharge : String, materials : [MaterialsSchema] }); var CatalogSchema = new Schema({ name : {type: String, index: true}, referenceId : ObjectId, pattern : String, categories : [CategoriesSchema], description : String, specifications : String, price : String, cost : String, pattern : String, thumbnailPath : String, primaryImagePath : String, styles : [StyleSchema] }); mongoose.connect('mongodb://127.0.0.1:27017/sc'); exports.Catalog = mongoose.model('Catalog', CatalogSchema); 

在CategoriesSchema,ColorsSchema和MaterialsSchema中定义的数据不会经常更改,如果有的话。 我决定将目录模型中的所有数据更好,因为虽然存在多个类别,颜色和材质,但数量不会太多,而且我也不需要独立于目录查找任何数据。

但是我对将数据保存到模型感到困惑。 这里是我被困住的地方:

 var item = new Catalog; item.name = "Seat 1003"; item.pattern = "91003"; item.categories.push({year: 1998, make: 'Toyota', model: 'Camry', body: 'sedan' }); item.styles.push({name: 'regular', surcharge: 10.00, materials(?????)}); item.save(function(err){ }); 

用这样的嵌套embedded架构,如何将数据导入到embedded文档的材质和颜色中?

.push()方法似乎不适用于嵌套文档。

embedded式文档的数组确实有push方法。 初始创builditem后,只需添加embedded式文档:

 var item = new Catalog; item.name = "Seat 1003"; item.pattern = "91003"; item.categories.push({year: 1998, make: 'Toyota', model: 'Camry', body: 'sedan' }); var color = new Color({name: 'color regular', id: '2asdfasdfad', surcharge: 10.00}); var material = new Material({name: 'material regular', surcharge: 10.00}); var style = new Style({name: 'regular', surcharge: 10.00}); 

那么你可以将每个embedded式文档推送到他们的父母:

 material.colors.push(color); style.materials.push(material); item.styles.push(style); 

然后你可以保存整个对象数据库,就像你已经在做的那样:

 item.save(function(err){}); 

而已! 并且您有embedded式DocumentArrays。

有关您的代码的其他一些说明,您的目录模型中有两次模式。 而为了访问你的其他模型types,你还需要导出这些:

 exports.Catalog = mongoose.model('Catalog', CatalogSchema); exports.Color = mongoose.model('Colors', ColorsSchema); exports.Material = mongoose.model('Materials', MaterialsSchema); exports.Style = mongoose.model('Style', StyleSchema);