var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username:{type: String,lowercase: true, required: true,unique:true},
password:{type:String, required:true},
email:{type:String,required:true,lowercase:true,unique:true},
});
// mongoose middleware
UserSchema.pre('save',(req,res,next)=>{
var user = this;
bcrypt.hash(user.password,null,null,(err,hash)=>{
if(err) return next(err);
user.password = hash;
next();
});
});
module.exports = mongoose.model('User',UserSchema);
低于错误我无法找出错误
POST / users 200 58.468 ms - 14 /var/www/html/meanstacktutorial/app/models/user.js:17 下一个(); ^
ReferenceError: next is not defined
at bcrypt.hash (/var/www/html/meanstacktutorial/app/models/user.js:17:9)
at /var/www/html/meanstacktutorial/node_modules/bcrypt-nodejs/bCrypt.js:631:3
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...
当我设置密码加密然后它得到一些错误,如“next()未定义”为什么我不知道确切..我一直试图解决问题但我不能请帮助我谢谢你
答案 0 :(得分:0)
传递给预保存挂钩的函数只能将 next 作为参数。
您还传递了 req 和 res 。
请改为尝试:
UserSchema.pre('save', (next) => {
var user = this;
bcrypt.hash(user.password, null, null, (err, hash) => {
if(err) return next(err);
user.password = hash;
next();
});
});
我希望这会有所帮助。