【问题标题】:I cant save my users when I use bcrypt with mongoose pre当我将 bcrypt 与 mongoose pre 一起使用时,我无法保存我的用户
【发布时间】:2020-09-29 05:21:51
【问题描述】:

当我使用 bcrypt 中间件加密我的密码时,问题就开始了。 Whitout bcrypt 我可以拯救用户,但现在不行。

我的 users.js 文件

'use strict'

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const bcrypt = require('bcrypt')

const UserSchema = new Schema({
    email: { type: String, unique: true, lowercase: true },
    displayName: String,
    password: { type: String, select: false }
})

UserSchema.pre('save', (next) => {
    let user = this
    if (!user.isModified('password')) {
        return next();
    }

    bcrypt.genSalt(10, (err, salt) => {
        if (err) return next(err)

        bcrypt.hash(user.password, salt, null, (err, hash) => {
            if (err) return next(err)

            user.password = hash
            next();
        })
    })
})

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

我的 router.js 文件:

const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const User = require('./model/user')
const bcrypt = require('bcrypt')


router.post('/user', (req, res) => {
    console.log(req.body)
    let user = new User()
    user.email = req.body.email
    user.displayName = req.body.displayName
    user.password = req.body.password

    user.save((err, stored) => {
        res.status(200).send({
            user: stored
        })
    })
})

这是服务器响应:

{}

我的数据库不受影响...

【问题讨论】:

    标签: node.js mongoose bcrypt


    【解决方案1】:

    我可以在提供的代码中看到两个错误:

    1.预存中间件中的this不是用户文档实例

    箭头函数不提供自己的this绑定:

    在箭头函数中,this 保留封闭词法上下文的 this 的值。 [source]

    将您的代码更改为以下内容:

    UserSchema.pre('save', function (next) {
        const user = this;
        // ... code omitted
    });
    

    2。不处理重复键 MongoError

    请求可能会因MongoError: E11000 duplicate key error collection 而失败,因为email 字段是唯一的。你忽略了这样的失败,因为你的user.save() 中的storedundefined,所以来自服务器的响应将是一个空对象。

    要解决此问题,您需要在以下代码中添加处理程序:

    user.save((err, stored) => {
      if (err) {
        throw err; // some handling
      }
      res.status(200).send({user: stored});
    });
    

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2011-02-13
      相关资源
      最近更新 更多