使用 @nestjs/mongoose 时如何向 Mongoose 模式添加实例/静态方法?(打字稿问题)

Gre*_*mas 5 mongoose typescript nestjs

使用 vanilla Mongoose 时,可以直接向 Mongoose schemas 添加方法。Mongoose 文档很好地解决了这个问题,并且可以找到几个示例。

但是当您在 Nest 应用程序的上下文中使用 Mongoose 时呢?我希望我的 Mongoose 模式更像“Nest”,所以我使用了 Mongoose ( @nestjs/mongoose)的 Nest 包装器。但是,@nestjs/mongoose似乎缺少的文档。我能找到的与任何文档最接近的内容是在 Nest 应用程序中使用 MongoDB 的指南,其中仅包括 Mongoose 最绝对的基本用例。

在我看来,Mongoose 在 Nest 世界中的使用方式与 vanilla Mongoose 使用的方式大不相同。也许这只是缺乏对 TypeScript 或 Nest 的熟悉,但我似乎无法真正了解这些差异,而且缺乏示例也无济于事。

我在 StackOverflow 上看到了一些关于如何实现这一点的答案,例如:

  • 解决方案 1 -向 MySchema.methods 添加方法的示例解决方案
    • 此解决方案对我不起作用:TypeScript 仍然告诉我该类型不存在该属性。
  • 解决方案 2 -使用扩展 Model 的接口的示例解决方案
    • 虽然这种使用我需要的方法添加新接口的解决方案确实让 TypeScript 认识到该方法对该类型有效,但我不确定如何实际实现它。我无法编写实现该接口的类,因为它需要实现 60 多种 Mongoose 模型方法,而我尝试编写实现的任何其他地方都不适合我。

我怎么能做这样的事情?

架构

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type CatDocument = Cat & Document;

@Schema()
export class Cat {
  @Prop()
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;
}

export const CatSchema = SchemaFactory.createForClass(Cat);

// ** Add methods here? **
Run Code Online (Sandbox Code Playgroud)

服务

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}

  async findAll(): Promise<Cat[]> {
    // Call our custom method here:
    return this.catModel.doSomething();
  }
}

Run Code Online (Sandbox Code Playgroud)

quo*_*lpr 2

这是我设法做到的:

export type UserDocument = User & Document;

@Schema()
export class User extends Document {
  @Prop({ required: true, unique: true })
  email!: string;
  @Prop({ required: true })
  passwordHash!: string;

  toGraphql!: () => UserType;
}

export const UserSchema = SchemaFactory.createForClass(User);

UserSchema.methods.toGraphql = function (this: User) {
  const user = new UserType();

  user.id = this._id;
  user.email = this.email;

  return user;
};
Run Code Online (Sandbox Code Playgroud)

刚刚添加

toGraphql!: () => 用户类型;

去上课