So when users sign up via Google, Twitter or such, names can overlap. 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?
The err object has a message attribute that matches the error message the mongo shell would give. 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. 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.