How To Define Custom Query Helper In Mongoose Model With Typescript?
I want to define custom query helper using query helper api . Here the example: // models/article.ts import { Document, Schema, Model, model } from 'mongoose'; interface IArtic
Solution 1:
I've drafted a new version of @types/mongoose
that supports query helpers. See this answer for ways to install a modified @types
package. With my version, you should be able to write the following in models/article.ts
:
import { Document, Schema, Model, model, DocumentQuery } from'mongoose';
interface IArticle extendsDocument {
name: string;
}
interface IArticleModel extendsModel<IArticle, typeof articleQueryHelpers> {
someStaticMethod(): Promise<any>;
}
constArticleSchema = newSchema( { name: String } )
let articleQueryHelpers = {
byName(this: DocumentQuery<any, IArticle>, name: string) {
returnthis.find({ name });
}
};
ArticleSchema.query = articleQueryHelpers;
exportdefault model<IArticle, IArticleModel>('Article', ArticleSchema);
and then routes/article.ts
will work. If this works for you, then I will submit a pull request to the original package on DefinitelyTyped.
Post a Comment for "How To Define Custom Query Helper In Mongoose Model With Typescript?"