微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我将bcrypt与mongoose pre一起使用时,我无法保存用户

如何解决当我将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,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
        })
    })
})

这是服务器响应:

{}

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

解决方法

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

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

箭头功能不提供自己的this绑定:

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

将代码更改为以下内容:

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

2。无法处理重复键MongoError

由于MongoError: E11000 duplicate key error collection字段是唯一的,因此请求可能会因email而失败。您将忽略这种失败,并且由于stored中的user.save()undefined,来自服务器的响应将是一个空对象。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。