使用MongoDB创建唯一的ID(重复问题)
对于我创建的每个用户,分配了一个唯一的数字ID。 这是我要做的:
let UserId = await userModel.countDocuments();
UserId++;
// then add the user
问题是,对于几个不同的用户,我有时几次拥有相同的userId
。 我认为当几个人同时创建自己的帐户时,问题可能会出现。
事先感谢您的回答!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是对的,此代码容易竞争条件,因此一些用户可能会获得相同的标识符。
ObjectID/UUID
最好的替代方法是将ObjectID或UUID(又称GUID)作为标识符。这样,您可以同时生成多个标识符,而这些标识符不取决于彼此。如果使用ObjectID(MongoDB的默认方式),则在存储文档时也可以省略标识符。在这种情况下,数据库为您生成objectID并将其分配给_id字段。
整数ID
特别是在分布式系统中,很难以避免这种种族条件的方式同步整数标识符。
一个选项是将最后一个标识符存储在文档中,以便您可以使用MongoDB的文档级别锁定,例如:
而不是计算文档以获取下一个ID,而是向ID文档发出$ INC的更新。从返回的文档中,您为用户拿出ID值。如果同时创建了几个用户,则MongoDB断言他们的更新是按顺序进行的,因此每个用户都会获得唯一的ID。但是,请注意,ID是唯一的,但不一定是连续的。如果在检索ID后用户的插入物将失败,则会存在差距。
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.:
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.