0

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.

Nodal
  • 353
  • 2
  • 14

1 Answers1

1

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"
    }
    */
});
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • That is incredibly cool. Is there any way to get that value out from the callback function though? – Nodal Jan 20 '16 at 05:20
  • 1
    @Nodal It's a bit tricky, you have some answers here: http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function?lq=1 (check the linked "duplicate of" too), basically, you can't, you have to work with it. One of a proposed solution is using Promises, MongoJS doesn't support them but the official [mongodb](https://www.npmjs.com/package/mongodb) driver or [mongoose](https://www.npmjs.com/package/mongoose) (if you need advanced feature like ODM/ORM) do. – Shanoor Jan 20 '16 at 05:28
  • thanks again. I kind of predicted that answer. Still trying to get my head around promises - I understand the concept, but as with everything, struggle with implementation and syntax. Would I be right in thinking it might be worth ditching MongoJS? – Nodal Jan 20 '16 at 05:33
  • 1
    @Nodal, I can't work with async without Promises personally :p Regarding mongodb, the official driver has promises support, it's the only one I use for all direct operations (bulk insert, find, aggregate...). I keep Mongoose for specific usages. I never used MongoJS but no Promises is a deal breaker for me. A very good way to start using promises: https://github.com/stevekane/promise-it-wont-hurt – Shanoor Jan 20 '16 at 05:53
  • Thanks, I think I've been delaying the inevitable. Time to get on with these promises. If I can use them how I think I can, then MongoJS is going straight out the window (I didn't choose it in the first place). Thanks again, again. – Nodal Jan 20 '16 at 06:03