user.js 1 KB
Newer Older
Kim, Subin's avatar
Kim, Subin committed
1
const mongoose = require('mongoose');
Ha YeaJin's avatar
pages    
Ha YeaJin committed
2
3
const bcrypt = require("bcrypt");
const saltRounds = 10;
Kim, Subin's avatar
Kim, Subin committed
4
5
6

const { Schema } = mongoose;
const userSchema = new Schema({
Ha YeaJin's avatar
pages    
Ha YeaJin committed
7
    name: {
Kim, Subin's avatar
ㅁㅁ    
Kim, Subin committed
8
        type: String,
Ha YeaJin's avatar
pages    
Ha YeaJin committed
9
        required: true,
Kim, Subin's avatar
ㅁㅁ    
Kim, Subin committed
10
    },
Ha YeaJin's avatar
pages    
Ha YeaJin committed
11
    password: {
Kim, Subin's avatar
ㅁㅁ    
Kim, Subin committed
12
        type: String,
Ha YeaJin's avatar
pages    
Ha YeaJin committed
13
14
        
    },
15
16
17
18
19
20
21
22
23
24
25
    role: {
      type: String,
      default:'user',
    },
    answer:{
      type: String,
    },
    question: {
      type: String,
    },
  
Ha YeaJin's avatar
pages    
Ha YeaJin committed
26
27
28
29
30
    id: {
        type: Number,
        required: true,
    },
    
Kim, Subin's avatar
Kim, Subin committed
31
32
});

Ha YeaJin's avatar
pages    
Ha YeaJin committed
33
userSchema.pre("save", function (next) {
34
35
36
37
38
39
40
  let user = this; //User모델 자체를 가르킴.

  //model 안의 paswsword가 변경 또는 생성될 때 암호화
  if (user.isModified("password")) {
    bcrypt.genSalt(saltRounds, function (err, salt) {
      if (err) return next(err);
      bcrypt.hash(user.password, salt, function (err, hash) {
Ha YeaJin's avatar
pages    
Ha YeaJin committed
41
        if (err) return next(err);
42
43
        user.password = hash;
        next();
Ha YeaJin's avatar
pages    
Ha YeaJin committed
44
      });
45
46
47
48
49
    });
  } else {
    next();
  }
});
Ha YeaJin's avatar
pages    
Ha YeaJin committed
50
51


Kim, Subin's avatar
Kim, Subin committed
52
module.exports = mongoose.model('User', userSchema);