【发布时间】:2012-04-16 10:36:27
【问题描述】:
我已经阅读并重新阅读了几篇关于 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 模型中会更好,因为虽然有多个类别、颜色和材料,但不会有那么多,而且我不需要独立于 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() 方法似乎不适用于嵌套文档。
【问题讨论】: