Isaac Krementsov
Isaac Krementsov

Reputation: 706

How do I access a MongoDB object id during creation?

I have a website where I want to do something like this:

myModel.create({myObject}); //I want to access the automatically created objectId of this new document
refModel.create({refId:somehowAccessId});
//Or, without Mongoose
db.myCollection.insert({myObject});
db.refCollection.insert({refId:somehowAccessId})

How is that done (preferably without using a find query and a callback).

Upvotes: 1

Views: 383

Answers (1)

Nilesh Singh
Nilesh Singh

Reputation: 1750

You can use mongoose's .save for the purpose. Insert the object in the first model, save it, and upon receiving a success callback, use its _id for the second model,

let model = new myModel(myObject);
model.save(function(err, savedObject) {
   let accessId = savedObject._id;
   refModel.create({refId: accessId}); //or something similar
})

The same can be done without using mongoose

 db.myCollection.insert(objectToBeSaved, function(err, savedObject) {
   let accessId = savedObject._id;
   db.refCollection.insert({refId: accessId}); //or something similar
 })

Upvotes: 1

Related Questions