【问题标题】:Can't authenticate the user, not found in mongoDB无法验证用户,在 mongoDB 中找不到
【发布时间】:2018-05-07 05:23:33
【问题描述】:

用户在数据库中创建,检查了几次代码,没有语法错误,只是返回未定义,即使用户被创建。使用名称和密码进行发布请求时,请正确输入凭据。代码:

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 返回未定义。我在这里想念什么吗?这没有任何意义。我将回调更改为承诺,但仍然相同。在数据库中寻找用户时,我觉得我做错了什么。我试过 find({}) 但没有运气。

【问题讨论】:

  • 你能从 mongo 控制台找到吗?
  • 在基于 promise 的 mongoose findOne 中,您只能在 then 子句中获得文档。我还建议使用 exec()。
  • @MustafaMamun 我正在使用 Robo 3T 作为 mongo 控制台的替代品,但是是的,我也可以在控制台中看到它。
  • @tumulr 我到底需要在哪里使用它?

标签: node.js mongodb jwt


【解决方案1】:

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

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

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

【讨论】:

  • 因为 Usermodel 位于另一个名为 user.js 的文件中,所以我将它调用到我的 api.js 路由文档并将其分配给用户变量。这就是用户的来源。
  • 如果我使用了错误的变量,我想我会得到未定义的错误。现在看起来像这样:var user = require("../models/user");
猜你喜欢
  • 1970-01-01
  • 2019-08-20
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 2018-01-25
  • 2017-05-22
  • 2019-08-25
相关资源
最近更新 更多