node.js - 当我将 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
})
})
})
这是服务器响应:
{}
我的数据库不受影响...
解决方案
我可以在提供的代码中看到两个错误:
1.this
在预存中间件中不是用户文档实例
箭头函数不提供自己的this
绑定:
在箭头函数中,this 保留了封闭词法上下文的 this 的值。[资源]
将您的代码更改为以下内容:
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});
});
推荐阅读
- go - 如何从 golang 项目文件中获取图像路径
- html - 如何在 Flutter 的 html 字符串中使用 css-property?
- wordpress - 在 WordPress 中获取具有类别名称的类别详细信息数组
- ios - iOS instagram api 无法登录(可疑登录尝试)
- amazon-web-services - Amazon S3 请求使用率似乎很高
- flutter - 在 Flutter 中为小部件添加圆角阴影
- java - 音乐播放器音量Ctrl
- powershell - 如何选择文件并阅读使用 PowerShell 接收的按日期排序的内容?
- powershell - 从 Windows CMD 将数组传递给 PowerShell
- javascript - 如何使用 Gatsby 映射两次?