npm install bcrypt
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const userSchema = mongoose.Schema({
name: {
type: String,
maxlngth: 50
},
email: {
type: String,
trim: true,
unique: 1
},
password: {
type: String,
minlength: 5
},
lastname: {
type: String,
maxlength: 50
},
role: {
type: Number,
default: 0
},
image: String,
token: {
type: String
},
tokenExp: {
type: Number
}
})
userSchema.pre('save', function(next){
//비밀번호를 암호화 시킨다.
var user = this;
if(user.isModified('password')){
bcrypt.genSalt(saltRounds, function(err, salt) {
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
// Store hash in your password DB.
if(err) return next(err)
user.password = hash
next();
});
});
}
})
const User = mongoose.model('User', userSchema)
//userSchema를 DB에 User라는 이름의 collection에 등록하라는 뜻
module.exports = { User }
아래와 같이 비밀번호가 암호화 되있는 것을 확인할 수 있다.