const userSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please tell us your name!'], }, email: { type: String, required: [true, 'Please provide your email'], unique: true, lowercase: true, validate: [validator.isEmail, 'Please provide a valid email'], }, photo: String, password: { type: String, required: [true, 'Please provide a password'], trim: true, minlength: 8, }, passwordConfirm: { type: String, required: [true, 'Please confirm your password'], validate: { // This only works on CREATE or SAVE!! validator(el) { return el === this.password }, message: 'Password are not the same!', }, }, })
const User = mongoose.model('User', userSchema) module.exports = User
開啟 userModel.js,在存入 user 資料前做加密,會利用到 bycrpt.hash 方法
1 2 3 4 5 6 7 8 9 10 11 12 13
userSchema.pre('save', asyncfunction(next) { // Only run this function if password was actually modifeid if (!this.isModified('password')) return next()
// Hash the password with cost of 12 加密密碼 this.password = await bycrpt.hash(this.password, 12)
// Delete passwordConfirm field this.passwordConfirm = undefined
const userSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please tell us your name!'], }, email: { type: String, required: [true, 'Please provide your email'], unique: true, lowercase: true, validate: [validator.isEmail, 'Please provide a valid email'], }, photo: String, password: { type: String, required: [true, 'Please provide a password'], trim: true, minlength: 8, }, passwordConfirm: { type: String, required: [true, 'Please confirm your password'], validate: { // This only works on CREATE or SAVE!! validator(el) { return el === this.password }, message: 'Password are not the same!', }, }, })
userSchema.pre('save', asyncfunction (next) { // Only run this function if password was actually modifeid if (!this.isModified('password')) return next()
// Hash the password with cost of 12 this.password = await bycrpt.hash(this.password, 12)
// Delete passwordConfirm field this.passwordConfirm = undefined next() })
const User = mongoose.model('User', userSchema) module.exports = User