【问题标题】:How can I extends mongoose Model<T>?如何扩展猫鼬模型<T>?
【发布时间】:2020-09-30 09:35:27
【问题描述】:

使用 mongoose 和 typescript 我想创建一个 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 (在创建方法)?

【问题讨论】:

    标签: mongodb typescript mongoose


    【解决方案1】:

    您不能调用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 类型是什么样的。

    【讨论】:

    • Log 是export default mongoose.model&lt;ILog&gt;('Log', LogSchema);
    • 现在我收到了'Log' refers to a value, but is being used as a type here. Did you mean 'typeof Log'?ts(2749)
    • 我认为Log 是一种类型,因为您在使用extends BaseRepository&lt;Log&gt; 时将其用作类型。这里括号内的东西需要是一个类型。这应该可以工作:export class LogRepository extends BaseRepository&lt;ILog&gt; { protected model = Log; },因为您的模型 Log 满足所需的类型 Model&lt;ILog&gt;。
    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2019-10-06
    • 2018-03-04
    • 2018-07-15
    • 2014-12-09
    相关资源
    最近更新 更多