user2080367
user2080367

Reputation: 73

Does mongoose guarantee unique objectId while creating model object? If yes, how?

MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
var m = new MyModel();
... 
//Other application/process might add document with same object id. 
m.save();

m has _id set. Does mongoose guarantee it's unique by querying mongo while creating model object?

Upvotes: 4

Views: 5085

Answers (1)

Reto
Reto

Reputation: 3141

The mongodb docs specify how the ObjectId is generated (http://docs.mongodb.org/manual/reference/object-id/#ObjectIDs-BSONObjectIDSpecification).

ObjectId is a 12-byte BSON type, constructed using:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

The ObjectId is generated in the client side MongoDb Driver Code, running on the client machine.

-> For most real world cases this can be considered unique.

(if it is not unique enough for your application, you probably have a large enough staff on your team to have an expert on unique ids: https://stackoverflow.com/a/5694803/2766511)

MongoDb also automatically creates an index with property "unique: true" on each collection for this field, to ensure that no two documents have the same objectId. (http://docs.mongodb.org/master/core/index-single/#index-type-id, http://docs.mongodb.org/master/tutorial/create-a-unique-index/)

Upvotes: 2

Related Questions