[英]Mongoose find - return all that match at least one from query
我正在構建一個應用程序(MongoDB數據庫),用戶可以在其中注冊帳戶。 帳戶模型具有3個唯一的值:ID,用戶名和電子郵件。 我正在使用Mongoose v5.5.5進行查詢等。
當有人想注冊一個新帳戶時,我想進行一個查詢(findOne或查找),以查看是否存在具有該ID 或用戶名或郵件的用戶。 我認為下面的代碼可以工作。
let query = {
'id': sanitized.id,
'username': sanitized.username,
'mail': sanitized.mail
}
AccountModel.find(query, (error, data) => {
// Handle result
})
因此,可以說有一個用戶名為user1且電子郵件為user1@mail.com的用戶 。 現在,另一個用戶想要注冊用戶名user2,但使用與user1相同的電子郵件。
我怎么能執行已經被另一個用戶打開或用戶名或郵箱,這樣我可以告訴那些既相匹配的查詢?
我更喜歡使用一個查詢來保持代碼干凈,但是我還沒有找到解決方案。 希望有人能幫忙。
您可以使用$或聚合來傳遞不同的查詢
let query = {
'$or': [
{'id': sanitized.id},
{'username': sanitized.username},
{'mail': sanitized.mail}
]
}
這將返回與任何查詢匹配的所有文檔。 在我的系統中,實際上我在Promise.all中執行了兩個查詢,一個用於userName,一個用於userEmail,以便於驗證數據(結果[0] = userName,result [1] = userEmail)
例如
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.