使用猫鼬和打字稿,我想创建一个BaseRepository,在这里我可以避免一些重复的代码,例如创建,列出,更新和删除。
这就是我所拥有的:
模型
import mongoose, { Document, Schema } from 'mongoose';
export interface ILog extends Document {
description: string;
}
const LogSchema: Schema = new Schema({
description: { type: String, required: true, unique: true }
});
export default mongoose.model<ILog>('Log', LogSchema);
存储库
export class LogRepository extends BaseRepository<Log> {
protected model = Log;
}
BaseRepository
import { Document, Model } from 'mongoose';
export abstract class BaseRepository<T extends Model<T>> {
protected abstract model: T;
public find (): Promise<T[]> {
return this.model.find().exec();
}
public create (body: any): Promise<T> {
const data = new T(body);
return data.save();
}
public update (id: string, body: any): Promise<T | null> {
return this.model.findByIdAndUpdate(id, body).exec();
}
public async delete (id: string): Promise<number | undefined> {
const res = await this.model.deleteOne({ _id: id }).exec();
return res.n;
}
}
但是在BaseRepository,我得到Type 'T' does not satisfy the constraint 'Document'
;
另外,我怎么做新的T(在create方法上)?
答案 0 :(得分:0)
您不能呼叫new T()
,因为T是类型。如果this.model
是课程,那么您想要的就是调用const data = new this.model(body);
这通常有效:
export abstract class BaseRepository<T extends Document> {
protected abstract model: Model<T>;
public create (body: any): Promise<T> {
const data = new this.model(body);
return data.save();
}
但是我不确定您的Log
类型是什么样。