猫鼬findOne()没有给出期望的输出

时间:2019-09-08 10:45:29

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

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

我正在尝试检查用户是否已注册,以便可以使他能够登录,但是即使他已注册,该响应也始终为空。

这是我尝试登录但始终以找不到用户的方式答复的情况:

路由器代码:

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

1 个答案:

答案 0 :(得分:0)

我希望这会有所帮助。我获取了您的代码,将其重新设置为目标,如下面的示例所示。它按原样工作。

像这样设置模型(如果需要,可以在其自己的文件中):

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

以这种方式设置您的路由处理程序(如果愿意,请保存在其自己的文件中)。导入用户模型并按如下所示进行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' });
        }
    }
});