我有2个收藏品 产品如下所示
var ProductSchema = new Schema({
name: String,
id:[parts_id], // What should i change here to embed all the id's of parts collection in array
});
var partSchema =new Schema(
{
"_id":autogenrated id",
"price" : number,
"properties" : {
"battery type" : string,
"talktime" : string,
"weight" : number
},
});
var Product = mongoose.model("Product");
var product = new Product(
{
"_id":"auto generated Id",
"name" : "iphone 5",
}
and other is parts which look like this
var parts = mongoose.model("parts");
var parts = new parts(
{
"_id":autogenrated id",
"price" : "$650",
"properties" : {
"battery type" : "lithium",
"talktime" : "8 hours",
"weight" : 2.3
},
});
这两个集合有一对多的关系,很多是零件集合。我想将零件集合的id添加到用于引用的产品集合数组中。我怎么能用mongoose做到这一点?
的语法是什么答案 0 :(得分:0)
你试过吗
var ProductSchema = new Schema({
name: String,
parts:[{type:Schema.Types.ObjectId, ref: 'parts' }]],
});
顺便说一句,我认为在声明模型时需要包含模式:
var parts = mongoose.model('parts', partSchema);
var Product = mongoose.model('Product', ProductSchema);
此外,您应该考虑有关套管和单数/复数形式名称的一致命名约定。
由于您似乎正在尝试使用Mongoose
的关系模型,因此我将包含有关.populate()的文档。