MongoDB + Express:如何使用db.collection().findOne()或.find()验证登录凭据?

5 javascript database mongodb node.js express

我有一个POST请求,其中一个用户凭据作为登录页面中的对象,并被传递给API服务器,如下所示:

  loginUser(creds) {
    //creds is in the form of { username: bob, password: 123 }

    var request = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(creds),
    }

    fetch(`http://localhost:3000/api/login`, request)
    .then(res => res.json())
    .then(user => {
      console.log(user);
      console.log('Successful')
    })
    .catch(err => {
      console.log('Error is', err)
    })
  },
Run Code Online (Sandbox Code Playgroud)

API Server会像这样接收它:

//With .findOne()
    app.post('/api/login/', function(req, res) {
      console.log('Req body in login ', req.body)
      db.collection('users').findOne(req.body, function(err, isMatch) {
        console.log('ISMATCH IS: ' + isMatch)
        if(err) {
          console.log('THIS IS ERROR RESPONSE')
          res.json(err)
        } else {
          console.log('THIS IS ISMATCH RESPONSE')
          res.json(isMatch)
        }
      })
    })
Run Code Online (Sandbox Code Playgroud)

要么

//With .find()
    app.post('/api/login/', function(req, res) {
      console.log('Req body in login ', req.body)
      //console logs correctly as { username: bob, password: 123 }
      db.collection('users').find(req.body).next(function(err, isMatch) {
        console.log('ISMATCH IS: ' + isMatch)
        if(err) {
          console.log('THIS IS ERROR RESPONSE')
          res.json(err)
        } else {
          console.log('THIS IS ISMATCH RESPONSE')
          res.json(isMatch)
        }
      })
    })
Run Code Online (Sandbox Code Playgroud)

因此,使用传入的登录凭据,在API服务器内部,我想搜索我的'users'数据库以查看是否与传入的数据库匹配.但在这两种情况下,即使用户凭据与任何用户凭据不匹配,isMatch也始终null始终记录console.log('THIS IS ISMATCH RESPONSE')在数据库中.在客户端,我从来没有得到任何错误响应,总是记录console.log('Successful').

似乎无法弄清楚我错过了什么.我能做错什么?

谢谢

Luc*_*sta 1

我建议你先找到用户,然后比较密码,例如:

db.collection('users').findOne({ username: req.body.username}, function(err, user) {
        console.log('User found ');
        // In case the user not found   
        if(err) {
          console.log('THIS IS ERROR RESPONSE')
          res.json(err)
        } 
        if (user && user.password === req.body.password){
          console.log('User and password is correct')
          res.json(user);
        } else {
          console.log("Credentials wrong");
          res.json({data: "Login invalid"});
        }              
 });
Run Code Online (Sandbox Code Playgroud)