2012-04-02 124 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