这是一个小例子,我用mongoose在nestJS中管理这个
import { Schema } from 'mongoose';
import * as bcrypt from 'bcryptjs';
import { User } from './user.interface';
import { generateCode } from '../utils/helpers';
import { SMS_FROM, Twilio } from '../utils/twilio.lib';
const SALT = 10;
const UserSchema = new Schema(
{
firstName: {
type: String,
required: true,
trim: true,
},
lastName: {
type: String,
required: true,
trim: true,
},
phoneNumber: {
type: String,
required: true,
trim: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
trim: true,
},
role: {
type: String,
enum: ['patient', 'doctor', 'admin'],
required: true,
default: 'patient',
},
},
{
timestamps: true,
},
);
UserSchema.pre<User>('save', async function(next) {
if (!this.isModified('password')) return next();
try {
this.password = bcrypt.hashSync(this.password, SALT);
console.log('pre save hook triggered');
this.isDocUpdated = true;
next();
} catch (e) {
next(e);
}
});
UserSchema.method({
validatePassword: async function(password) {
return bcrypt.compareSync(password, this.password);
},
});
export { UserSchema };
您还必须为用户模式创建接口,并在注入模型时将模型类型转换为 UserInterface
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { IUser } from './user.interface';
export class UsersService {
private client: ClientProxy;
constructor(
@InjectModel('User') private readonly userModel: Model<IUser>,
) {}
}