diff --git a/User.js b/User.js new file mode 100644 index 0000000..981e48c --- /dev/null +++ b/User.js @@ -0,0 +1,44 @@ +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 + }, + role: { + type: String, + enum: ['student', 'teacher', 'admin'], + default: 'student' + }, + createdAt: { + type: Date, + default: Date.now + } +}); + +// 密码加密中间件 +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 (err) { + next(err); + } +}); + +// 密码验证方法 +userSchema.methods.comparePassword = async function (candidatePassword) { + return await bcrypt.compare(candidatePassword, this.password); +}; + +module.exports = mongoose.model('User', userSchema); \ No newline at end of file