我想设置自定义模型方法以编辑字段,这是一个复杂的结构。例如,为了切换完成待办事项的状态。
类似这样的东西:
@Schema()
export class User extends Document {
@Prop({ type: [{ title: String, complete: Boolean }], default: [] })
todos: Todo[];
}
const UserSchema = SchemaFactory.createForClass(User);
UserSchema.methods.toggleComleteTodo = (id: string) => {
// code...
}
我做错了什么?在哪里可以找到正确的代码?在docs nestjs中,关于自定义猫鼬方法=(
答案 0 :(得分:0)
这是一个小例子,很热,我用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>,
) {}
}