@类型鹅/打字鹅“:"^7.2.0”
有没有办法用类型圈和类型鹅来建立通用的CRUD存储库?特别是,如何使getModelForClass()方法与泛型一起工作?类似于从问题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;
}发布于 2020-06-27 15:24:13
参考文献:https://github.com/typegoose/typegoose/issues/303
如果您想要一个"manager类“而不是实际的模型是泛型的,这很容易,您只需要有正确的类型。
我建议把这门课写成:
// 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泛型被删除了)
https://stackoverflow.com/questions/62599137
复制相似问题