我想用数据库检查我的输入。如果输入 == 集合中的数据,则转到下一页
我尝试成功,但它只检查数组中的第一个值。
此代码是创建数据到数据库 [成功]
app.post('/register',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let myobj = { Email: req.body.email, Password: req.body.psw } ;
dbo.collection("Register").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log(" document inserted");
db.close();
});
});
res.render('whatsub');
});
这段代码是我插入循环的问题
app.post('/index',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("project");
dbo.collection("Register").findOne({}, function(err, result) {
if (result.Email == req.body.email && result.Password == req.body.psw) {
console.log("Correct go next page");
}
else{
console.log("Wrong email/password");
}
db.close();
});
});
});
是否可以使用 forEach 检查集合中的所有数据?
从 Mongo 中选择所有记录,然后与您的用户名和密码进行比较是不好的做法。
只要你调用 Mongo,你的代码就会选择findOne
的第一条记录,所以它甚至不会做任何循环,因为它只返回一条记录(数据库中的第一条(
但是,最好执行以下操作,从 mongo 中选择userName
等于passed userName
,然后将您在请求中发送的password
与存储在数据库中的进行比较。
//select from mongo collection where email equals the one being passed in req's body [make sure you spell names correctly]
dbo.collection("Register").findOne({email: req.body.email} , function(err, result) {
//make sure result is not null, compare Password stored in mongo with the one passed in req's body
if (result && result.Password == req.body.psw) {
console.log("Correct go next page");
}
else{
console.log("Wrong email/password");
}
});