【问题标题】:Mongodb, Typegoose - generic repository patternMongodb,Typegoose - 通用存储库模式
【发布时间】:2020-10-17 07:33:27
【问题描述】:

@typegoose/typegoose": "^7.2.0"

有什么方法可以使用 typecirpt 和 typegoose 获得通用 CRUD 存储库? 特别是,如何让getModelForClass() 方法与泛型一起工作? 类似于从question 246 借来的这段代码。

如果是这样,我错过了什么?

import { prop, getModelForClass } from '@typegoose/typegoose';
import { AnyParamConstructor, ReturnModelType } from '@typegoose/typegoose/lib/types';

export class GenericCRUDService<T, U extends AnyParamConstructor<T> = AnyParamConstructor<T>> {
  dataModel: ReturnModelType<U, T>;

  constructor(cls: U) {
    this.dataModel = getModelForClass<T, U>(cls);
  }

  public create(data: T) {
    this.dataModel.create(data);
  }
}

export class Cat {
  @prop()
  public age: number;
  @prop()
  public color: string;
}

export class Dog {
  @prop()
  public isBarking: boolean;
  @prop()
  public race: string;
}

【问题讨论】:

    标签: mongodb typescript mongoose typegoose


    【解决方案1】:

    参考:typegoose/typegoose#303

    如果你想要一个“管理器类”而不是真正的模型是通用的,这很简单,你只需要有正确的类型

    我会建议编写这样的类:

    // NodeJS: 14.4.0
    // MongoDB: 4.2-bionic (Docker)
    import { getModelForClass, prop, types, ReturnModelType, DocumentType } from "@typegoose/typegoose"; // @typegoose/typegoose@7.2.0
    import * as mongoose from "mongoose"; // mongoose@5.9.18 @types/mongoose@5.7.27
    
    export class GenericCRUDService<U extends types.AnyParamConstructor<any>> {
      public dataModel: ReturnModelType<U>;
    
      constructor(cls: U) {
        this.dataModel = getModelForClass(cls);
      }
    
      public create(data: mongoose.CreateQuery<DocumentType<InstanceType<U>>>) {
        this.dataModel.create(data);
      }
    }
    
    export class Cat {
      @prop()
      public age?: number;
    
      @prop()
      public color?: string;
    }
    
    export class Dog {
      @prop()
      public isBarking?: boolean;
    
      @prop()
      public race?: string;
    }
    
    (async () => {
      await mongoose.connect(`mongodb://localhost:27017/`, { useNewUrlParser: true, dbName: "verifyMASTER", useCreateIndex: true, useUnifiedTopology: true });
    
      const CatService = new GenericCRUDService(Cat);
    
      await CatService.create({}); // with type support (since ~@types/mongoose@5.7.21)
    
      await mongoose.disconnect();
    })();
    

    (以旧示例为例,您的问题是,由于 7.1.0 删除了“不必要的”T 泛型)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2012-09-05
      • 2016-02-12
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多