无法使用mongoose,node.js,express和async函数更新文档数据

时间:2018-12-17 12:19:50

标签: node.js express mongoose async-await

我正在尝试创建一个登录功能,该功能可以接收用户的电子邮件以及密码。

  1. 检查电子邮件是否存在-有效
  2. 检查密码是否与db中的加密密码匹配-有效

  3. 如果1 + 2是true->生成令牌并将令牌设置到用户文档中。但是它不起作用,操作user.token =令牌无效,邮递员没有响应。

我在做什么错了?

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const User = require('../models/user');

exports.login = async (req, res, next) => {
        const email = req.body.email;
        const password = req.body.password;

        let emailExist = await User.findOne({ email: email }).then(user => {
            if (!user) {
                return res.json({ isAuth: false, message: 'Login failed, email not found' });
            }
            return user;
        });

        let isPasswordMatch = await bcrypt.compare(password, emailExist.password);

        if (!isPasswordMatch) {
            return res.json({ isAuth: false, message: 'Login failed, wrong password' });
        }

        let loadedUser = await User.findOne({ email: email, password: emailExist.password })
            .then(user => {
                if (!user) {
                    return res.json({ isAuth: false, message: 'Login failed' });
                }
                return user;
            })
            .then(user => {
                const token = jwt.sign({ role: user.role, email: user.email, userId: user._id.toString() }, 'secret');
                console.log(user);

                user.token = token;
                return user.save();
            });

        res.status(200)
            .cookie(('auth', token))
            .json({ isAuth: true, token: token, user: loadedUser });
    };

更新版本:(仍然不起作用) 现在它给了我以下错误:

  

(节点:11336)UnhandledPromiseRejectionWarning:CastError:Cast to   数字值失败   “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjowLCJlbWFpbCI6ImFoQGdtYWlsLmNvbSIsInVzZXJJZCI6IjVjMTc4NDc3Mzg5MWI5MjY5MGNkMzgwNiIsImlhdCI6MTU0NTA1MTY5OX0.8GWuV82A7yOvKKkXeOjIeYve5aH0YwBEK_RuH0NVfYA”   在“令牌”路径上

exports.login = async (req, res, next) => {
    const email = req.body.email;
    const password = req.body.password;

    let emailExist = await User.findOne({ email: email });

    if (!emailExist) {
        return res.json({ isAuth: false, message: 'Login failed, email not found' });
    }

    let isPasswordMatch = await bcrypt.compare(password, emailExist.password);

    if (!isPasswordMatch) {
        return res.json({ isAuth: false, message: 'Login failed, wrong password' });
    }

    let loadedUser = await User.findOne({ email: email, password: emailExist.password });

    let token = jwt.sign(
        {
            role: loadedUser.role,
            email: loadedUser.email,
            userId: loadedUser._id.toString()
        },
        'secret'
    );

    console.log('token === ', token);
    console.log('user before token === ', loadedUser);

    updateUserToken = await loadedUser.update({ $set: { token: token } });

    console.log('user === ', loadedUser);

    res.status(200)
        .cookie(('auth', token))
        .json({ isAuth: true, token: token, user: updateUserToken });
};

1 个答案:

答案 0 :(得分:0)

检查您的用户模型文件,查看是否已将令牌添加为数字。如果是这样,这可能是问题所在。尝试将其更改为 string