【问题标题】:how i can set custom methods for mongoose model with @nestjs/mongoose package?如何使用 @nestjs/mongoose 包为 mongoose 模型设置自定义方法?
【发布时间】:2020-10-17 01:27:11
【问题描述】:

我想设置自定义模型方法以编辑复杂结构的字段。例如,为了切换完成待办事项的状态。
类似这样的:

@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 中没有关于自定义 mongoose 方法的内容 = (

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

    这是一个小例子,我用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>,
      ) {}
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 2011-11-17
      • 2021-09-01
      • 2021-01-01
      • 2018-12-11
      • 2020-11-11
      • 2020-06-16
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多