【问题标题】:Mongoose findOne() is not giving desired outputMongoose findOne() 没有提供所需的输出
【发布时间】:2020-01-10 11:10:35
【问题描述】:

我正在制作一个需要登录系统的全栈网站当用户注册他的数据成功插入数据库时​​,我正在使用 mongoose 将我的项目与 mongodb 连接起来,问题是登录时我尝试查找已注册的电子邮件始终以未找到用户的方式回复。

我正在尝试检查用户是否已注册,以便我可以让他能够登录,但即使他已注册,它也总是以 null 响应。

这是我尝试登录但总是以未找到用户的方式响应:

路由器代码:

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;

// the problem is here in the findOne function 

 User.findOne({ email:email }).then(user => {
    if (!user) {
      return res.status(404).json({ email: "User not found" });
    }

    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        res.json({ msg: "Success" });
      } else {
        return res.status(400).json({ password: "password incorrect" });
      }
    });
  });
});

架构代码:

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

const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model("users", UserSchema);

【问题讨论】:

  • 如果您删除bcrypt.compare(password, user.password) 部分,并在成功时删除return user,它会在您的情况下正常工作吗? user 是否通过email 字段找到了自己,他存在吗?
  • 感谢您的回答,但没有,因为他不能只使用电子邮件登录,代码的问题是即使找到了电子邮件,它也没有进入下一步检查密码是否正确
  • 用户通过他的电子邮件被检查是否被找到,所以如果他没有找到它说用户没有找到但是如果他被找到然后他检查密码是否正确如果它不正确然后它说密码不正确
  • 我理解了你代码的逻辑,我说如果你删除bcryct 通过哈希密码检查,findOne 方法是否可以通过电子邮件正确找到用户?只需回复我:“是或否”。并在您发表下一条评论时尝试使用逗号。
  • 不,它给了我同样的“找不到用户”

标签: node.js mongodb express mongoose mongodb-atlas


【解决方案1】:

我希望这会有所帮助。我拿走了你的代码,重新调整了它的用途,如下例所示。它按原样工作。

像这样设置你的模型(如果你愿意的话,在它自己的文件中):

// Your mongoose model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password_hash: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model("User", UserSchema, 'users');

像这样设置你的路由处理程序(如果你愿意的话,在它自己的文件中)。导入 User 模型和 bcrypt,如下所示。注意我添加了 /register 路由。这是向您展示如何处理注册和存储密码。

const bcrypt = require('bcrypt');
const User = require('../model/so.user.model');

// Note: Login route for demo purposes
router.post('/login', async (req, res) => {
    const { email, password } = req.body;
    console.log({email, password});
    // Note: Basic validity check for demo purposes
    if (!email || !password) {
        res.status(400).json({ message: 'No data provided' });
    } else {
        const user = await User.findOne({ email });
        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }
        try {
            isMatch = await bcrypt.compare(password, user.password_hash);
            if (isMatch) {
                res.status(200).json({ message: `Login successful for ${user.name}` });
                /* ==== Response sent to client =====
                    {
                        "message": "Login successful for Grey"
                    } 
                */
            } else {
                return res.status(400).json({ password: 'password incorrect' });
            }
        } catch (error) {
            return res.status(500).json({ error, message: 'Something went wrong' });
        }
    }

});

// Note: Registration route for demo purposes
router.post('/register', async (req, res) => {
    const { name, email, password } = req.body;
    const saltRounds = 4;

    // Note: Basic validity check for demo purposes
    if (!name || !email || !password) {
        res.status(400).json({ message: 'No data provided' });
    } else {
        try {
            const password_hash = await bcrypt.hash(password, saltRounds);
            const newUser = User({
                name,
                email,
                password_hash
            });
            savedUser = await newUser.save();
            res.status(201).json({
                message: 'User created successfully',
                data: savedUser
            });

            /* ====== Response sent to client =============
                {
                    "message": "User created successfully",
                    "data": {
                    "__v": 0,
                    "name": "Grey",
                    "email": "grey@asheori.com",
                    "password_hash": "$2b$04$Lu5FeGmSLzuVv2pctO7pQOBbK/wnETr6TqaWXcshUwpcjPA3fXo/G",
                    "_id": "5d75ab74f5f93903fb2d3305",
                    "date": "2019-09-09T01:31:32.235Z"
                    }
                } 
            */

        } catch (error) {
            res.status(500).json({ message: 'Something went wrong' });
        }
    }
});

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    相关资源
    最近更新 更多