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
}
}
In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.
Mongoose save with an existing document will not override the same object reference. New! Save questions or answers and organize your favorite content. Learn more.
Here mongoose will check if there is a collection called "Users" exists in MongoDB if it does not exist then it creates it. The reason being, mongoose appends 's' to the model name specified. In this case 'User' and ends up creating a new collection called 'Users'.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With