[英]How to define custom query helper in mongoose model with typescript?
I want to define custom query helper using query helper api . 我想使用查询助手API定义自定义查询助手。 Here the example:
这里的例子:
// models/article.ts
import { Document, Schema, Model, model } from 'mongoose';
interface IArticle extends Document {
name: string;
}
interface IArticleModel extends Model<IArticle> {
someStaticMethod(): Promise<any>;
}
const ArticleSchema = new Schema( { name: String } )
ArticleSchema.query.byName = function(name) {
return this.find({ name })
}
export default model<IArticle, IArticleModel>('Article', ArticleSchema);
// routes/article.ts
import ArticleModel from '../models/article.ts'
router.get('/articles, (req, res) => {
ArticleModel.find().byName('example')
})
Typescript complains about byName
method when I chain it with defaults. 当我使用默认链接时,Typescript抱怨
byName
方法。
I can put it in IArticleModel
interface but in that case I could only call it from model. 我可以将其放在
IArticleModel
接口中,但在那种情况下,我只能从模型中调用它。
Where should I put the definition of this method to use it in chainable way? 我应该在哪里放置此方法的定义以可链接的方式使用它?
I've drafted a new version of @types/mongoose
that supports query helpers. 我已经草拟了支持查询助手的
@types/mongoose
的新版本 。 See this answer for ways to install a modified @types
package. 有关安装修改后的
@types
软件包的方法, @types
答案 。 With my version, you should be able to write the following in models/article.ts
: 使用我的版本,您应该能够在
models/article.ts
编写以下内容:
import { Document, Schema, Model, model, DocumentQuery } from 'mongoose';
interface IArticle extends Document {
name: string;
}
interface IArticleModel extends Model<IArticle, typeof articleQueryHelpers> {
someStaticMethod(): Promise<any>;
}
const ArticleSchema = new Schema( { name: String } )
let articleQueryHelpers = {
byName(this: DocumentQuery<any, IArticle>, name: string) {
return this.find({ name });
}
};
ArticleSchema.query = articleQueryHelpers;
export default model<IArticle, IArticleModel>('Article', ArticleSchema);
and then routes/article.ts
will work. 然后
routes/article.ts
将起作用。 If this works for you, then I will submit a pull request to the original package on DefinitelyTyped. 如果这对您有用,那么我将向DefinitelyTyped上的原始包提交拉取请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.