Unique ID creation with MongoDB (duplicate problem)

Viewed 44

for each user I create, a unique number ID is assigned. Here is what I do:

let UserId = await userModel.countDocuments();
UserId++;

// then add the user

The problem is that I sometimes have the same UserId several times, for several different users. I think the problem can come when several people create their account at the same time.

Thanks in advance for your answer!

1 Answers

You are right that this code is prone to race conditions so that several users might get the same identifier.

ObjectId/UUID

The best alternative would be to use either an ObjectId or an UUID (a.k.a. Guid) as the identifier. This way, you can generate several identifiers at the same time that do not depends on each other. If you use an ObjectId (Mongodb's default way) you can also omit the identifier when storing the document. In this case, the database generate an ObjectId for you and assigns it to the _id field.

Integer ids

Especially in a distributed system it is harder to synchronize the generation of integer identifiers in a way that you avoid such race conditions.

One option is to store the last identifier in a document so that you can use MongoDB's document level locking, e.g.:

{
  _id: ObjectID('abc...'),
  lastId: 123
}

Instead of counting the documents to get the next id, you issue an update with $inc to the id-document. From the returned document, you take the id value for the user. If several users are created at the same time, Mongodb asserts that they updates are carried out in sequence so that each user gets a unique id. However, please note that the ids are unique but not necessarily consecutive. If the insert of a user fails after the id was retrieved, there will be a gap.

Related