2012-04-02 87 views
5

我已阅读并重新阅读有关Mongoose中嵌入和链接文档的几篇文章。基于我已阅读,我的结论是,这将是最好有类似以下的模式结构:如何填充嵌套的Mongoose嵌入式文档

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定义不会经常变化的数据,如果有的话。我决定在Catalog模型中包含所有数据会更好,因为虽然存在多个类别,颜色和材质,但数量不会太多,而且我也不需要独立于目录查找其中的任何数据。

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

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){ 

}); 

这样嵌套的嵌入式模式,如何获取数据到材料和颜色嵌入式文档?

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

回答

7

嵌入文档数组的确有push方法。只需添加嵌入文档后最初创建item

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}); 

,那么你可以把每一个嵌入文档到他们父母:

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

然后您可以将数据库保存整个对象,你在那里已经这样做:

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

就是这样!你有嵌入式DocumentArrays。

关于您的代码的一些其他说明,您的目录模型中有两次pattern。并且为了访问您的其他模型类型,您还需要导出这些模型:

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

如果集合中有很多目录。我们将如何推到特定的ID? – 2017-01-06 10:51:39