Static Mongoose Model Definitions in Typescript

I created a Mongoose schema and added some static methods for a model called Campaign.

If I console.log Campaign, I see the methods present on it. The problem is that I don’t know where to add these methods so that Typescript also knows about them.

If I add them to my CampaignModelInterface, they are only available for model instances (or at least TS think they are).

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 

I also tried to access it through Campaign.schema.statics, but with no luck.

Can anyone tell me how to tell TS about the methods present in the model, and not in the model instances?

+5
source share
1 answer

I answered a very similar question here , although I will answer yours (basically the third section of my other answer), since you provided a different scheme. There is a useful readme with typical Mongoose types that are pretty hidden, but there is a section on static methods .


The behavior you described is completely normal - Typescript reports that the schema (an object that describes individual documents) has a method called getLiveCampaigns .

Instead, you need to tell Typescript that the method is on the model, not on the diagram. After that, you can access the static methods according to the regular Mongoose method. You can do it as follows:

 // 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 
+4
source

Source: https://habr.com/ru/post/1270739/


All Articles