Reputation: 353
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
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