简体   繁体   English

当MongoDB上的唯一索引失败时生成替代方案

[英]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: 所以这里有两个问题:

  1. How can I check if err is a unique index error? 如何检查err是否是唯一索引错误?
  2. What is the most efficient way to append an unique suffix to the user's name? 将唯一后缀附加到用户名称的最有效方法是什么?
  1. 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 } 
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM