2017-08-10 20 views
5

私はMongoose Schemaを作成し、モデルにはCampaignという静的メソッドをいくつか追加しました。Mongoose静的モデル定義(Typescript)

私はconsole.logキャンペーンに私はそこに存在するメソッドを見ることができます。問題は、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 

私もCampaign.schema.statics経由でアクセスしようとしたが、運なし。

モデルのインスタンスではなく、モデルに存在するメソッドについてTSに知らせる方法はありますか?

答えて

4

hereと非常によく似た質問に答えましたが、別のスキーマを提供しているので、私はあなたの回答に答えます。モンゴースの入力には便利なreadmeがありますが、これはかなり隠されていますが、static methodsに関するセクションがあります。


あなたが説明した動作が完全に正常である - 活字体は、スキーマ(個々のドキュメントを記述するオブジェクトが)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 
+0

ありがとうございます!私はあなたの元の答えに遭遇しなかったのを驚いた。 あなたが示唆したように、それを働かせることができた。 正しく取得したら、私はすべてのSchema.staticメソッドをCampaignModelInterfaceに、そしてすべてのSchema.methodメソッドをCampaignDocumentInterfaceに入れます。 –

+0

私は個人的に 'CampaignDocumentInterface'に' CampaignSchema'で定義されているようなスキーマだけが含まれるように設定しました。 'CampaignInterface'には' Schema.method'メソッドがすべて含まれ、 'CampaignModelInterface'にはすべての' Schema.static'メソッドが含まれています。 –

+0

あなたは 'CampaignDocumentInterface'で' Schema.method'メソッドを宣言することもできます。私は個人的に分離を好むだけです。 –

関連する問題