Reputation: 256
I am trying to create a mongodb collection called products in which I have fields (id, name, price and properties) and now different products have different kind of properties for example iphone has different set of properties when compared to nike shoes. So how to define a schema and add dynamically new key and value pair using mongoose.
{
"_id":"001",
"name":"iphone 5",
"price":$650,
"properties":{
'weight':2.3,
'talktime': '8 hours',
'battery type': 'lithium'
}
}
{
"_id":"002",
"name":"nike shoes",
"price":$80,
"properties":{
'size':10,
'color':black
}
}
Upvotes: 11
Views: 14647
Reputation: 23420
Take a look at Mongoose's Mixed schema type: http://mongoosejs.com/docs/schematypes.html. If you specify that type for an attribute ({}
) it will allow anything to be saved to it.
For example:
var ProductSchema = new Schema({
name: String,
price: String,
properties: {}
});
mongoose.model("Product", ProductSchema);
var Product = mongoose.model("Product");
var product = new Product({
"name": "iphone 5",
"price": "$650",
"properties": {
"weight": 2.3,
"talktime": "8 hours",
"battery type": "lithium"
}
});
product.save();
After running the code above, the database now contains this document:
{
"name" : "iphone 5",
"price" : "$650",
"properties" : {
"battery type" : "lithium",
"talktime" : "8 hours",
"weight" : 2.3
},
"_id" : ObjectId("53b35ca575e9d7a40de0edb7"),
"__v" : 0
}
Upvotes: 15