我在架构上使用pre函数进行“保存”,以在保存之前对密码进行哈希处理。但是出现错误。 schemaName.pre不是函数。
我尝试使用验证而不是保存,但这也无法正常工作。
const userSchema = {
name: {
required: true,
type: String,
trim: true
},
email: {
type: String,
required: true,
trim: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
age: {
type: Number,
validate(value) {
if (value < 0) {
throw new Error('Age must be positive number')
}
}
},
password: {
type: String,
required: true,
trim: true,
minlength: 7,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Canno contain the string "Password".')
}
}
}
}
userSchema.pre('save', async function (next) {
const user = this
console.log('just before saving')
next()
})
我想在将密码保存到数据库之前先对其进行哈希处理。
答案 0 :(得分:0)
也许它对你有用。您可以编写这样的预保存方法。 它为我工作。请尝试这个。
Pila
答案 1 :(得分:0)
您是否正在使用猫鼬创建架构?在您的代码中,我看到的只是纯js对象。 像这样尝试:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcryptjs');
var userSchema = new Schema({
name: {
required: true,
type: String,
trim: true
},
email: {
type: String,
required: true,
trim: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
age: {
type: Number,
validate(value) {
if (value < 0) {
throw new Error('Age must be positive number')
}
}
},
password: {
type: String,
required: true,
trim: true,
minlength: 7,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Canno contain the string "Password".')
}
}
}
});
// reference from above answer
userSchema.pre('save', async function(next) {
console.log('just before saving');
const rounds = 10;
const hash = await bcrypt.hash(this.password, rounds);
this.password = hash;
next();
});
希望这会有所帮助:)
答案 2 :(得分:0)
我在散列密码时遇到了同样的问题。最终,以下解决了它。 之前我用过,
this.password = bcrypt.hash(this.password, 12); this.cpassword = bcrypt.hash(this.cpassword, 12);
答案 3 :(得分:0)
const mongooose = require('mongoose');
const bcrypt =require('bcryptjs')
const user = new mongooose.Schema({
name: {
type: String,
required:true
},
email: {
type: String,
required:true
},
password: {
type: String,
required:true
},
cpassword: {
type: String,
required:true
}
})
user.pre('save',async function(next){
if(this.isModified('password')){
this.password = await bcrypt.hash(this.password,12);
this.cpassword =await bcrypt.hash(this.cpassword,12);
}
next();
})
const User = mongooose.model('USER', user);
module.exports = User;