本文介绍了创建锁定,以便两个用户不使用相同的用户名创建帐户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我使用Express服务器与Node.js,并关注并发,并阻止用户同时创建具有相同用户名的帐户。从我的underatanding,尽管主要的Node.js运行时是单线程的事实,仍然可能一个函数开始,而另一个尚未完成。 一个选项是在外部源(如Redis)上创建一个锁,并使用它来控制并发性 - 但我的问题是 - 是否有一个强大的方法来控制本地JavaScript?例如,某个层次的嵌套函数基本上保证一个新的请求在另一个完成之前不会启动某个调用(我怀疑)。I am using the Express server with Node.js and am concerned about concurrency and preventing users from creating accounts with the same username at the same time. From my underatanding, despite the fact that the primary Node.js runtime is single-threaded, it may still be possible for one function to begin while another one has yet to complete.One option is to create a lock on an external source like Redis, and use that to control concurrency - however my question is - is there a robust way to control this in native JavaScript? For example, is a certain level of nested functions basically going to guarantee that a new request won't initiate a certain call before another completes (I doubt it).更具体 - 我使用MongoDB与Mongoose。在使用Mongoose模式的内存中应该有一个唯一的用户列表。所以会发生什么:To be more specific - I am using MongoDB with Mongoose. There should be a unique list of users in memory using Mongoose schemas. So what could happen:(1)新用户注册用户名A(1) new user registers with username A将A与索引的用户列表进行比较,发现A确实是新用户名(2) node.js compares A with indexed list of users, and finds that A is indeed a new username(3)node.js进行DB调用以将A添加到列表(3) node.js makes a DB call to add A to list(4)before(3)完成用户名A的新用户注册... node.js将A与用户名索引进行比较,所以它发送一个插入到DB(4)before (3) finishes a new user registers with username A...node.js compares A with the username index and it looks unique so it sends an insert to the DB这个问题似乎是真的。the problem seems real. My guess is that best way to solve it is an external lock.推荐答案解决这个问题的最直接的方法是使用唯一索引对应的mongo集合。这将防止任何会导致重复值的插入或更新(注意,这是由mongodb服务器强制,而不是mongoose)。The most straightforward way of solving this is with a unique index on the corresponding mongo collection. This will prevent any inserts or updates that would cause duplicate values (Note that this is enforced by the mongodb server, not mongoose).我不熟悉mongoose,但是当你告诉它一个属性是唯一的,它会创建相应的唯一索引。I'm not familiar with mongoose, but it would seem that when you tell it that an attribute is unique it creates the corresponding unique index. 这篇关于创建锁定,以便两个用户不使用相同的用户名创建帐户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!