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

const { Schema } = mongoose;
const userSchema = new Schema({
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  name: {
    type: String,
    required: true,
  },
  password: {
    type: String,

  },
  id: {
    type: Number,
    required: true,
  },
  question: {
    type: String,
  },
  answer: {
    type: String,
  },

Ha YeaJin's avatar
pages    
Ha YeaJin committed
26
27
28
});

userSchema.pre("save", function (next) {
29
30
31
32
33
34
35
  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
36
        if (err) return next(err);
37
38
        user.password = hash;
        next();
Ha YeaJin's avatar
pages    
Ha YeaJin committed
39
      });
40
41
42
43
44
    });
  } else {
    next();
  }
});
Ha YeaJin's avatar
pages    
Ha YeaJin committed
45
46
47


module.exports = mongoose.model('User', userSchema);