4
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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user2080367
  • 73
  • 1
  • 5
  • It does. One part of id is a random hash and another is a unique counter common accross collections. – Héctor Sep 10 '15 at 17:30

1 Answers1

2

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/)

Community
  • 1
  • 1
Reto
  • 3,107
  • 1
  • 21
  • 33
  • Thanks for the details. We have to guarantee guarantee it's uniqueness. But I missed last part in documentation, that is, it adds "unique:true" property, which will trigger some error. – user2080367 Sep 10 '15 at 22:02
  • yes, the unique: true index guarantees it "in this one collection" - the algorithm "almost" guarantees it universally. – Reto Sep 11 '15 at 07:36