在Typescript中的Mongoose静态模型定义

Dan*_*itu 6 typescript mongoose-schema mongoose-models

我创建了一个Mongoose Schema并为Model添加了一些名为Campaign的静态方法.

如果我是console.log Campaign我可以看到它上面的方法.问题是我不知道在哪里添加这些方法,以便Typescript也知道它们.

如果我将它们添加到我的CampaignModelInterface,它们仅适用于模型的实例(或者至少TS认为它们是).

campaignSchema.ts

  export interface CampaignModelInterface extends CampaignInterface, Document {
      // will only show on model instance
  }

  export const CampaignSchema = new Schema({
      title: { type: String, required: true },
      titleId: { type: String, required: true }
      ...etc
  )}

  CampaignSchema.statics.getLiveCampaigns = Promise.method(function (){
      const now: Date = new Date()
      return this.find({
           $and: [{startDate: {$lte: now} }, {endDate: {$gte: now} }]
      }).exec()
  })

  const Campaign = mongoose.model<CampaignModelInterface>('Campaign', CampaignSchema)
  export default Campaign
Run Code Online (Sandbox Code Playgroud)

我也试过通过Campaign.schema.statics访问它,但没有运气.

任何人都可以建议如何让TS了解模型中存在的方法,而不是模型实例?

Har*_*ton 8

我在这里回答了一个非常类似的问题,虽然我会回答你的问题(主要是我的另一个答案的第三部分),因为你提供了一个不同的架构.有一个有用的自述文件与Mongoose类型相当隐藏,但有一节关于静态方法.


您描述的行为是完全正常的 - Typescript被告知Schema(描述单个文档的对象)具有调用的方法getLiveCampaigns.

相反,您需要告诉Typescript该方法是在模型上,而不是模式.完成后,您可以按照常规的Mongoose方法访问静态方法.你可以通过以下方式做到这一点:

// CampaignDocumentInterface should contain your schema interface,
// and should extend Document from mongoose.
export interface CampaignInterface extends CampaignDocumentInterface {
    // declare any instance methods here
}

// Model is from mongoose.Model
interface CampaignModelInterface extends Model<CampaignInterface> {
    // declare any static methods here
    getLiveCampaigns(): any; // this should be changed to the correct return type if possible.
}

export const CampaignSchema = new Schema({
    title: { type: String, required: true },
    titleId: { type: String, required: true }
    // ...etc
)}

CampaignSchema.statics.getLiveCampaigns = Promise.method(function (){
    const now: Date = new Date()
    return this.find({
        $and: [{startDate: {$lte: now} }, {endDate: {$gte: now} }]
    }).exec()
})

// Note the type on the variable, and the two type arguments (instead of one).
const Campaign: CampaignModelInterface = mongoose.model<CampaignInterface, CampaignModelInterface>('Campaign', CampaignSchema)
export default Campaign
Run Code Online (Sandbox Code Playgroud)

  • @Mykola [定义](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/f40ab95d0548a7544a5515228595095dd21741c7/types/mongoose/index.d.ts#L157) 的模型类型&lt;文件扩展`T文档,U 扩展了 Model&lt;T&gt;&gt;`。因此顺序是`model&lt;CampaignInterface, CampaignModelInterface&gt;(...)`。 (2认同)