Nodal
Nodal

Reputation: 353

How to get the unique id of a MongoDB object when inserting

I am working on a NodeJS express app using MongoDB (currently using Mongojs) and am not able to figure out how to do a certain thing with it.

I need to insert an object into a collection, and immediately get this new insert's unique identifier to store as a variable for use later in the app. I am very new to using Mongo, but as far as I can tell there is a '_id' field automatically generated as a primary key for any collection? This seems like what I need, correct me if I'm wrong.

Any assistance would be greatly appreciated. Thanks again.

Upvotes: 0

Views: 714

Answers (1)

Shanoor
Shanoor

Reputation: 13692

With MongoJS, you can use a callback on collection.save() or collection.insert(), for example:

db.myCollection.save({
    foo: 'foo',
    bar: 'bar'
}, function (err, doc) {
    // here, the doc will have the generated _id
    console.log(doc);
    /* output:
    {
        "foo": "foo",
        "bar": "bar",
        "_id": "569f1730fde60ac030bc223c"
    }
    */
});

Upvotes: 1

Related Questions