下面是您问题的解决方案:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique:true,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
userSchema.pre('save', function() {
console.log(this.password);
this.password = bcrypt.hashSync(this.password);
console.log(this.password);
});
module.exports = mongoose.model('User', userSchema);
我用来运行解决方案的代码:
exports.create = async function () {
let user = new User({
email : '[email protected] /cdn-cgi/l/email-protection',
username: 'new username',
password: '123abc'
});
return await user.save()
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
};
你的第一个问题是你不能使用箭头函数在这种类型的方法中:同样的错误已解决 https://stackoverflow.com/questions/37365038/this-is-undefined-in-a-mongoose-pre-save-hook
第二个问题是你需要调用bcrypt.hashSync方法,如果你不想处理 Promise。
关于您的架构的一项观察,所有字段都是唯一的。这个属性唯一:真实将在数据库中创建索引,并且您将无法通过密码找到该用户。这里是 Moongose 文档:猫鼬文档 http://mongoosejs.com/docs/validation.html
对于初学者来说,一个常见的问题是模式的唯一选项不是验证器。它是构建 MongoDB 唯一索引的便捷助手。请参阅常见问题解答以获取更多信息。