4

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(...);
dlebech
  • 1,817
  • 14
  • 27

1 Answers1

4

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471