[英]Mongoose find - return all that match at least one from query
I'm building an application (MongoDB database) where user can register an account. 我正在构建一个应用程序(MongoDB数据库),用户可以在其中注册帐户。 The account model has 3 value's that should be unique: ID, Username & Email. 帐户模型具有3个唯一的值:ID,用户名和电子邮件。 I'm using Mongoose v5.5.5 for querying etc. 我正在使用Mongoose v5.5.5进行查询等。
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. 当有人想注册一个新帐户时,我想进行一个查询(findOne或查找),以查看是否存在具有该ID 或用户名或邮件的用户。 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 . 因此,可以说有一个用户名为user1且电子邮件为user1@mail.com的用户 。 Now another user wants to register user the username user2 but with the same email as user1. 现在,另一个用户想要注册用户名user2,但使用与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) 在我的系统中,实际上我在Promise.all中执行了两个查询,一个用于userName,一个用于userEmail,以便于验证数据(结果[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 }
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.