2

I'm building an application (MongoDB database) where user can register an account. The account model has 3 value's that should be unique: ID, Username & Email. I'm using Mongoose v5.5.5 for querying etc.

When someone wants to register a new account, I want to do a query (findOne or find) to see if there is a user with that ID OR username OR mail. I thought the code below would work.

let query = {
  'id': sanitized.id,
  'username': sanitized.username,
  'mail': sanitized.mail
}

AccountModel.find(query, (error, data) => {
  // Handle result
})

So lets say there is a user with as username user1 and as email user1@mail.com. Now another user wants to register user the username user2 but with the same email as user1.

How can I perform a query that matches on OR the username OR the mail so that I can tell either of those is already being used by another user?

I prefer using one single query to keep the code clean, but I couldn't find a solution yet. Hope someone can help.

2 Answers2

7

You can use $or aggregation to pass different queries

 let query = {
      '$or': [
          {'id': sanitized.id},
          {'username': sanitized.username},
          {'mail': sanitized.mail}
      ]
    }

This will return all documents matching any of the queries. In my system what I did is actually two queries in Promise.all, one for userName, one for userEmail, for easier validation of the data (result[0] = userName, result[1] = userEmail)

Eg

Promise.all([
  AccountModel.find({'username': sanitized.username}).exec(),
  AccountModel.find({'mail': sanitized.mail}).exec(),
]).then(validation => {
  if(validation[0]){// username taken }
  if(validation[1]){// email taken }
})
noitse
  • 1,045
  • 9
  • 27
0

You can still you the Find method just when you do your query use the $or operator and here's an example

Andrei
  • 1,196
  • 1
  • 11
  • 25