2

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}}});

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i have given same as above coding but it is showing error in semicolon.$push:{"Mywant":{ _id: new mongodb.ObjectID(); "title":"car", "rate":$100}} is this correct syntax or not? i think it is wrong syntax.
1

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();

2 Comments

if i update new data into array it would not create new object id.so tell me correct answer.
I have updated my answer with a link to a JavaScript library for generating ObjectIds
0

In javascript there is one method called Math.random() it will create dynamic random number so you can modify this number as dynamic id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.