简体   繁体   中英

Mongoose find - return all that match at least one from query

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.

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 }
})

您仍然可以在使用$or 运算符进行查询时使用Find 方法 ,这是一个示例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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