feat: add backend server

This commit is contained in:
2026-05-11 16:01:22 +08:00
parent 3c838d534f
commit e24a34deb4
11 changed files with 1709 additions and 0 deletions

47
server/model/user.js Normal file
View File

@@ -0,0 +1,47 @@
import mongoose from 'mongoose'
import bcrypt from 'bcrypt'
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
index: true,
},
nickname: {
type: String,
},
password: {
type: String,
required: true,
},
role: {
type: String,
enum: ['admin', 'user'],
default: 'user',
},
},
{ timestamps: true }
)
// 保存前自动对密码进行哈希加密
UserSchema.pre('save', async function () {
this.password = await bcrypt.hash(this.password, 10)
})
// 实例方法:校验密码
UserSchema.methods.comparePassword = async function (candidatePassword) {
return bcrypt.compare(candidatePassword, this.password)
}
// 输出时始终不返回密码
UserSchema.methods.toJSON = function () {
const obj = this.toObject()
delete obj.password
return obj
}
const User = mongoose.model('User', UserSchema)
export default User