[英]Generate Alternative when Unique Index fails on MongoDB
So when users sign up via Google, Twitter or such, names can overlap. 因此,当用户通过Google,Twitter等注册时,名称可能会重叠。 Within my app, usernames have a unique index. 在我的应用程序中,用户名具有唯一索引。 Since a new document is put into the collection whenever someone signs in for the first time, sometimes the unique index fails. 由于每当有人第一次登录时都会将新文档放入集合中,因此有时唯一索引会失败。 The code for signing up a user goes like this: 注册用户的代码如下:
module.exports.findOrCreateUser = (provider, id, data, done) ->
User.findByAuth provider, id, (err, user) ->
if err? then done err
else if user? then done null, user
else
user = new User
auth: [{id: id, provider: provider}]
name: data.name
email: data.email
user.save (err) ->
if err? then done err else done null, user
So I have two problems here: 所以这里有两个问题:
err
is a unique index error? 如何检查err
是否是唯一索引错误? The err
object has a message
attribute that matches the error message the mongo shell would give. err
对象的message
属性与mongo shell提供的错误消息相匹配。 Checking if there's a unique index error should look something like this: 检查是否存在唯一索引错误应如下所示:
if (err && err.message.indexOf('E11000 ') !== -1) { // this _id was already inserted in the database }
I agree with @innoSPG to append the service name to username. 我同意@innoSPG将服务名称附加到用户名。 If you don't want indication of the service associated with the username just append a counter to the username and increment it every time it's used. 如果您不希望指示与用户名关联的服务,只需在用户名后附加一个计数器,并在每次使用时递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.