首页 > 解决方案 > 当我将 bcrypt 与 mongoose pre 一起使用时,我无法保存我的用户

问题描述

当我使用 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.jsmongoosebcrypt

解决方案


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

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

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

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

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

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

2.不处理重复键MongoError

MongoError: E11000 duplicate key error collection由于email字段是唯一的,因此请求可能会失败。你忽略了这样的失败,因为storeduser.save()undefined服务器的响应将是一个空对象。

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

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

推荐阅读