TypeScript 中的查询助手
¥Query Helpers in TypeScript
查询助手 允许你在 Mongoose 查询上定义自定义辅助程序方法。查询助手使用链接语法使查询更加语义化。
¥Query helpers let you define custom helper methods on Mongoose queries. Query helpers make queries more semantic using chaining syntax.
以下是查询助手如何在 JavaScript 中工作的示例。
¥The following is an example of how query helpers work in JavaScript.
ProjectSchema.query.byName = function(name) {
return this.find({ name: name });
};
const Project = mongoose.model('Project', ProjectSchema);
// Works. Any Project query, whether it be `find()`, `findOne()`,
// `findOneAndUpdate()`, `delete()`, etc. now has a `byName()` helper
Project.find().where('stars').gt(1000).byName('mongoose');
手动输入查询助手
¥Manually Typed Query Helpers
在 TypeScript 中,你可以使用单独的查询助手接口定义查询助手。Mongoose 的 Model
采用 3 个通用参数:
¥In TypeScript, you can define query helpers using a separate query helpers interface.
Mongoose's Model
takes 3 generic parameters:
DocType
TQueryHelpers
型¥a
TQueryHelpers
typeTMethods
型¥a
TMethods
type
第二个通用参数 TQueryHelpers
应该是一个包含每个查询助手的函数签名的接口。下面是使用 byName
查询辅助程序创建 ProjectModel
的示例。
¥The 2nd generic parameter, TQueryHelpers
, should be an interface that contains a function signature for each of your query helpers.
Below is an example of creating a ProjectModel
with a byName
query helper.
import { HydratedDocument, Model, QueryWithHelpers, Schema, model, connect } from 'mongoose';
interface Project {
name?: string;
stars?: number;
}
interface ProjectQueryHelpers {
byName(name: string): QueryWithHelpers<
HydratedDocument<Project>[],
HydratedDocument<Project>,
ProjectQueryHelpers
>
}
type ProjectModelType = Model<Project, ProjectQueryHelpers>;
const ProjectSchema = new Schema<
Project,
Model<Project, ProjectQueryHelpers>,
{},
ProjectQueryHelpers
>({
name: String,
stars: Number
});
ProjectSchema.query.byName = function byName(
this: QueryWithHelpers<any, HydratedDocument<Project>, ProjectQueryHelpers>,
name: string
) {
return this.find({ name: name });
};
// 2nd param to `model()` is the Model class to return.
const ProjectModel = model<Project, ProjectModelType>('Project', ProjectSchema);
run().catch(err => console.log(err));
async function run(): Promise<void> {
await connect('mongodb://127.0.0.1:27017/test');
// Equivalent to `ProjectModel.find({ stars: { $gt: 1000 }, name: 'mongoose' })`
await ProjectModel.find().where('stars').gt(1000).byName('mongoose');
}
自动键入查询助手
¥Auto Typed Query Helpers
Mongoose 确实支持结构选项中提供的自动类型查询助手。查询助手函数可以定义如下:
¥Mongoose does support auto typed Query Helpers that it are supplied in schema options. Query Helpers functions can be defined as following:
import { Schema, model } from 'mongoose';
const ProjectSchema = new Schema({
name: String,
stars: Number
}, {
query: {
byName(name: string) {
return this.find({ name });
}
}
});
const ProjectModel = model('Project', ProjectSchema);
// Equivalent to `ProjectModel.find({ stars: { $gt: 1000 }, name: 'mongoose' })`
await ProjectModel.find().where('stars').gt(1000).byName('mongoose');