Node.js Mongoose findOne()未提供所需的输出

Node.js Mongoose findOne()未提供所需的输出,node.js,mongodb,express,mongoose,mongodb-atlas,Node.js,Mongodb,Express,Mongoose,Mongodb Atlas,我正在制作一个完整的网站,在那里我需要登录系统。我正在使用mongoose将我的项目与mongodb连接。当用户注册他的数据并成功插入数据库时,问题是登录时,当我试图查找已注册的电子邮件时,它总是以未找到用户的方式响应 我试图检查用户是否已注册,以便让他能够登录,但即使他已注册,它也始终以null响应 这是当我尝试登录时,但总是以“未找到用户”进行响应: 路由器代码: router.post("/login", (req, res) => { const email = req.bod

我正在制作一个完整的网站,在那里我需要登录系统。我正在使用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);
架构代码:

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,如下所示。注意,我添加了一个/注册路由。这是为了向您展示如何处理注册和存储密码

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

如果您删除
bcrypt.compare(password,user.password)
部分,并在成功时
返回用户
,它在您的情况下是否正常工作?
user
是否通过
email
字段找到自己,他存在吗?谢谢回答,但没有,因为他不能只使用电子邮件登录代码的问题是,即使在找到电子邮件时,也无法进入下一步检查密码是否正确用户的电子邮件检查是否找到了用户,因此如果找不到,则表示找不到用户,但如果找到了,则检查密码是否正确密码正确如果密码不正确,则表示密码不正确我理解您代码的逻辑,我说如果您通过哈希密码删除
bcryct
检查,则
findOne
方法是否通过电子邮件正确查找用户?回答我:“是或不是”。下次发表评论时请尽量使用逗号。否,它给出的是相同的“未找到用户”