首页 > 解决方案 > 使用 express 查找单个 mongo 文档

问题描述

我是 MongoDB 的新手,特快。我想用他的用户名和密码验证用户。但即使我使用正确的凭据,我的代码也没有给出任何错误并执行“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>

标签: javascriptmongodbexpress

解决方案


这两行

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");
    }
})

希望能帮助到你


推荐阅读