[英]how to add an id's of one collection to arrays of id of other collection using mongoose
I have 2 collections one is Products which looks like the following 我有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
},
});
and these two collections have one to many relationship, many being the parts collection. 这两个集合具有一对多的关系,其中很多是零件集合。 I want to add the id's of parts collection into an array of products collection for referencing.
我想将零件集合的ID添加到产品集合数组中以供参考。 How can I do that using mongoose and what is the syntax for that
我如何使用猫鼬来做到这一点,它的语法是什么
Have you tried 你有没有尝试过
var ProductSchema = new Schema({
name: String,
parts:[{type:Schema.Types.ObjectId, ref: 'parts' }]],
});
By the way, I think you need to include the schema when declaring the model: 顺便说一句,我认为您在声明模型时需要包括模式:
var parts = mongoose.model('parts', partSchema);
var Product = mongoose.model('Product', ProductSchema);
Also, you should consider a consistent naming convention regarding casing and singular/plural forms of the names. 另外,您应考虑有关名称的大小写和单/复数形式的一致命名约定。
Since it looks like you are attempting a relational model with Mongoose
, I'm including the documentation regarding .populate() . 由于看起来您正在尝试使用
Mongoose
建立关系模型,因此我包含了有关.populate()的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.