dlebech
dlebech

Reputation: 1839

MongoDB: Can I use a created ObjectId before saving my document

Using mongoose on node.js:

Can I access the _id field on a model before it has been saved to the database and be sure that the ID will not change?

For example, I would like to do the following:

var model = new mongoose.model('MyModel');
someOtherObject.myModelId = String(model._id);

// Some more code...

model.save(...);

Upvotes: 4

Views: 2698

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

In Mongoose, _id values must always be assigned client-side as the docs indicate that:

Mongoose forces the db option forceServerObjectId false and cannot be overridden.

So the model._id value you get in the first line of your code will not be changed unless you do it in your own code before calling model.save.

Upvotes: 4

Related Questions