无法对用户进行身份验证,在mongoDB中找不到

时间:2017-11-23 09:42:30

标签: node.js mongodb jwt

用户在数据库中创建,多次检查代码,没有语法错误,只返回undefined,甚至创建用户。使用名称和密码发出请求时,也可以正确输入凭据。代码:

var mongoose = require("mongoose");
  var Schema = mongoose.Schema;

var User = new Schema({
      name: String,
      password: String,
    admin: Boolean
});

var Usermodel = mongoose.model("user", User);
module.exports = Usermodel;

router.post('/authenticate', function(req, res) {

  // find the user
  user.findOne({
    name: req.body.name
  }).then(function(err, user) {
    console.log(user);
    if (err) throw err;

    if (!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    } else if (user) {

      // check if password matches
      if (user.password != req.body.password) {
        res.json({ success: false, message: 'Authentication failed. Wrong password.' });
      } else {

        // if user is found and password is right
        // create a token with only our given payload
    // we don't want to pass in the entire user since that has the password
    const payload = {
      admin: user.admin
    };
        var token = jwt.sign(payload, 'superSecret', {
          expiresIn: 60*60*24 // expires in 24 hours
        });

        // return the information including token as JSON
        res.json({
          success: true,
          message: 'Enjoy your token!',
          token: token
        });
      }

    }

  });
});

所有必需的依赖项,我没有得到任何错误的控制台,只是if语句找不到我创建的用户,console.log返回undefined。我在这里错过了什么吗?这没有任何意义。我将回调改为承诺,但仍然如此。在DB中查找用户时,我觉得我做错了什么。我试过找({})但没有运气。

1 个答案:

答案 0 :(得分:0)

由于你使用的是user.find,你的用户变量是什么,你在哪里声明了这个?

您正在将用户架构模型分配给 Usermodel

您的查询应为Usermodel.findOne({name:req.body.name})

相关问题