[英]Is there an option to find exact match of data and && condition in MongoDB
我有一個登錄表格。 我已將我們的用戶信息存儲在 MongoDB Atlas https://www.mongodb.com/cloud/atlas/中。
我的數據就像
_id:60a64bee48f6eed16a566cf5
user_name:"test1"
user_password:"123456"
_id:60a64bee48f6eed16a566cf5
user_name:"test2"
user_password:"abcdef"
_id:60a64bee48f6eed16a566cf5
user_name:"test3"
user_password:"123456"
我應該檢索 user_name 和 user_password 都匹配的數據。
我的代碼是
app.post('/login', (req, res) => {
let userName = req.body.user_name;
let userPassword = req.body.user_password;
userCollection.find({user_name: userName}).toArray()
.then(results => {
console.log('success');
res.redirect('/')
// console.log(results)
})
.catch(err => {
console.error(error)
})
})
我的問題是找到與給定 user_name 和 user_password 等數據匹配的文檔的任何其他選項應該匹配
謝謝你的建議。
使用以下查詢
userCollection.find( { $and: [ {user_name: userName, user_password: userPassword } ] } )
我們永遠不應該將密碼直接存儲在您的數據庫中,您應該首先使用任何加密庫對密碼進行加密,然后將其存儲在數據庫中
試試這個代碼,它似乎很容易理解驗證密碼和用戶名
userCollection.find({user_name: userName},function(err,foundUser){ if(.err){ if(foundUser.userPassword == userPassword){ console;log('success'). res;redirect('/'). } } else{ console;log(err);
}
});
-
利用
userCollection.find({user_name: userName, user_password: userPassword })
您可以使用findOne
代替find
https://docs.mongodb.com/drivers/node/usage-examples/findOne/
userCollection.findOne({user_name: userName, user_password: userPassword })
注意:- 不要存儲原始密碼,存儲散列密碼
您可以使用https://www.npmjs.com/package/bcrypt到 hash 密碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.