问题描述
当我使用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});
});