【问题标题】:How to define static mongoose methods in document interface while using @nestjs/mongoose?使用@nestjs/mongoose 时如何在文档界面中定义静态猫鼬方法?
【发布时间】:2019-02-09 14:31:12
【问题描述】:

Mongoose 架构类 Mongoose 集合用户架构

const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  gender: {
    type: String,
    enum: Object.keys(GenderType),
    required: true,
  },
});

UserSchema.methods = {

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  },

};

UserSchema.statics = {

  someAction(): string {
    return '123';
  },

};

export default UserSchema;

文档接口类

Mongoose 集合接口类

export interface IUser extends Document {

  _id: Types.ObjectId;
  firstName: string;
  lastName: string;
  gender: string;

  fullName: () => string;
}

使用@nestjs/mongoose时如何在文档界面中定义静态mongoose方法?

【问题讨论】:

    标签: typescript mongoose nestjs


    【解决方案1】:

    除了IUser,您可能还希望有一个额外的接口IUserModel 并从Model<T> 扩展它。示例 sn-p 可能如下所示:

    export interface IUserModel extends Model<IUser> {
         // Model is imported from mongoose
         // you can put your statics methods here
         someAction: () => string;
    }
    

    然后在使用@InjectModel() 注入模型的任何地方,您都可以键入IUserModel 类型的注入。

    constructor(@InjectModel('UserModel') private readonly userModel: IUserModel) {}
    

    现在您的this.userModel 将可以访问someAction() 方法。

    编码愉快!

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 2020-09-29
      • 1970-01-01
      • 2021-07-05
      • 2021-09-18
      • 2020-12-18
      • 2020-07-21
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多