File size: 1,218 Bytes
4c025e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006ee19
 
 
 
 
 
4c025e9
 
 
 
 
006ee19
4c025e9
 
006ee19
 
 
 
 
 
 
4c025e9
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
      required: [true, '请输入用户名'],
      unique: true,
      trim: true,
    },
    password: {
      type: String,
      required: [true, '请输入密码'],
      minlength: [6, '密码长度不能小于6个字符'],
    },
    isAdmin: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

// 密码匹配方法
userSchema.methods.matchPassword = async function (enteredPassword) {
  try {
    return await bcrypt.compare(enteredPassword, this.password);
  } catch (error) {
    console.error('密码比较出错:', error);
    return false;
  }
};

// 保存前加密密码
userSchema.pre('save', async function (next) {
  if (!this.isModified('password')) {
    return next(); // 修复:确保不重复加密
  }

  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

const User = mongoose.model('User', userSchema);

module.exports = User;