Reputation: 1457
I have data like this
Mywants:[
{"title":"lap","rate":$20}
{"title":"lap","rate":$20}
{"title":"lap","rate":$20}
]
If I save new data into array(mywant) I should save with new unique id so how to save like that using javascript. So it should be look like:
Mywants:[
{"title":"lap","rate":$20,_id:objectId("512640f3243c837c0e0004401}
{"title":"lap","rate":$20,_id:objectId("512640f3243c837254000001}
{"title":"lap","rate":$20,_id:objectId("512640f3243c8372540257001}}
]
To insert I am using command like
collection.update({"userid":1248787885},{$push:{"Mywant":{"title":"car","rate":$100}}});
Upvotes: 2
Views: 2825
Reputation: 311865
As andyb notes, you have to generate the ObjectId
for your new element by constructing a new one. But you don't need a separate library:
var mongodb = require('mongodb');
collection.update(
{"userid":1248787885},
{$push:{"Mywant":{
_id: new mongodb.ObjectID(),
"title":"car",
"rate":$100
}}});
Of course, $100
isn't a valid JavaScript type, but I assume you know that. It's also worth noting that Mongoose does this adding of _id
fields to array elements for you, so that's another alternative.
Upvotes: 2
Reputation: 43823
To generate mongoDB ObjectId
in JavaScript you can use an existing library or implement the BSON ObjectId specification yourself. ObjectId.js is one such library and getting an Id is as simple as:
var objectId = new ObjectId();
Upvotes: 1
Reputation: 227
In javascript there is one method called Math.random() it will create dynamic random number so you can modify this number as dynamic id.
Upvotes: 0