使用express查找单个mongo文档



我是MongoDB的新手,express。我想用用户名和密码验证用户。但是,即使使用了正确的凭据,我的代码也不会给出任何错误并执行"else语句"。

这是JS文件:

app.post('/auth', function(req, res){
var user = ( db.collection('auth').findOne({name: req.body.username}));
var pass = ( db.collection('auth').findOne({password: req.body.password}));
if(user == req.body.username && pass == req.body.password){
res.send("Credentials Match");
}else{
res.send("Wrong Credentials");
}
console.log(req.body);
})

这是HTML文件:

<form class="form-signin" action="/auth" method="POST">
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputEmail" class="sr-only">Username</label>
<input type="text" placeholder="Username" name="username" required="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" placeholder="password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>

这两行

var user = ( db.collection('auth').findOne({name: req.body.username}));
var pass = ( db.collection('auth').findOne({password: req.body.password}));

表示异步代码,因此if else检查不会等待它们执行

除非您订购javascript等待

可以使用async/await强制代码等待异步部分完成

此外,你只得到用户名,然后只得到密码太

因此,如果用户输入了自己的名字,但输入了另一个密码,而不是正确的密码,并且这个密码存在于数据库中,则登录将完成,而不应该进行

你必须检查同一文档中的用户名和密码,以避免

类似的东西

app.post('/auth', async function(req, res) { // note the async keyword here
try {
var user = await db.collection('auth').findOne({ name: req.body.username , password: req.body.password });
if (user && user.name == req.body.username && user.password == req.body.password) {
res.send("Credentials Match");
} else {
res.send("Wrong Credentials");
}
console.log(req.body);
}
catch (err) {
console.log('Exception >>n', err); // log the error
res.send("Something wrong has happened while checking the credentials");
}
})

希望它能帮助

findOne方法返回一个文档。因此,与字符串的比较可能总是失败。你需要做的是先拿到一份文件。

var user = db.collection('auth').findOne({name: req.body.username, password: req.body.password});

这将为您返回具有您要查找的名称和密码组合的用户。现在你只需要问用户us是null还是一个文档,然后你就可以基于if/else了。

我建议将您当前的var用户和var密码记录到控制台中(通过console.log((方法(,这样您就可以看到自己犯了什么错误。

然后把我提供给你的那行打印出来,看看它有什么不同。试着用"错误"的密码做这件事,看看你会得到什么样的返回类型。通过这种方式,您可以适应if/else条件。

最新更新