Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add dynamic field to existing collection using mongoose

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
  }
}
like image 683
Yash Avatar asked Jul 01 '14 18:07

Yash


People also ask

What is _v in Mongoose?

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.

What does save () do in Mongoose?

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.

Does Mongoose save overwrite?

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.

Does Mongoose create collection automatically?

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'.


1 Answers

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
}
like image 69
dylants Avatar answered Oct 06 '22 17:10

dylants