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

时间:2018-09-04 14:12:13

标签: typescript mongoose nestjs

猫鼬模式类 猫鼬收集用户模式

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;

文档界面类

猫鼬收集接口类

export interface IUser extends Document {

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

  fullName: () => string;
}

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

1 个答案:

答案 0 :(得分:0)

除了IUser外,您可能还需要一个额外的接口IUserModel并将其从Model<T>扩展。示例代码段可能如下所示:

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()方法。

编码愉快!