如何使用打字稿在猫鼬模型中定义自定义查询助手? [英] How to define custom query helper in mongoose model with typescript?
问题描述
我想使用 查询助手 api 定义自定义查询助手.示例如下:
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 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 会抱怨 byName
方法.
我可以将它放在 IArticleModel
接口中,但在这种情况下,我只能从模型中调用它.
我应该把这个方法的定义放在哪里才能以可链接的方式使用它?
Typescript complains about byName
method when I chain it with defaults.
I can put it in IArticleModel
interface but in that case I could only call it from model.
Where should I put the definition of this method to use it in chainable way?
推荐答案
我已经起草了 新版本的 @types/mongoose
支持查询助手.请参阅此答案,了解安装修改后的 @types
包的方法.使用我的版本,您应该能够在 models/article.ts
中编写以下内容:
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 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);
然后 routes/article.ts
将起作用.如果这对您有用,那么我将向绝对类型的原始包提交拉取请求.
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.
这篇关于如何使用打字稿在猫鼬模型中定义自定义查询助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!