节点.JS Schema.pre('save) 不会更改数据



我正在制作用户授权系统,希望在将密码保存到DB之前对其进行哈希处理。为了达到这个目的,我使用bcrypt nodejs。上述标题中的问题;

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = new mongoose.Schema({
email: { 
type: String,
unique: true,
required: true,
},
username: {
type: String,
unique: true,
required: true
},
password: { 
type: String,
unique: true,
required: true
}
});
userSchema.pre('save', (next) => {
var user = this;
bcrypt.hash(user.password, bcrypt.genSaltSync(10), null, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
})
});
module.exports = mongoose.model('User', userSchema);

下面是问题的解决方案:

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 : 'test@test.com',
username: 'new username',
password: '123abc'
});
return await user.save()
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
};

您的第一个问题是不能在这种类型的方法中使用箭头函数:相同错误已解决

第二个问题是,如果您不想处理Promises,则需要调用bcrypt.hashSync方法。

关于你的模式的一个观察结果是,所有的字段都是唯一的。此属性unique:true将在数据库中创建索引,并且您不会通过密码找到用户。这里的moongose文档:Moogose文档

对于初学者来说,一个常见的难题是模式的唯一选项不是验证器。它是构建MongoDB唯一索引的方便助手。有关详细信息,请参阅常见问题解答。

最新更新