我正在尝试让中间件使用Typescript,但pre
和post
中的this和next都不能正常工作,我不知道我做错了什么。
schema.pre("updateOne", function (this: IDepartment, next: HookNextFunction) {
console.log("pre update department"); // <- logs: pre update department
console.log(this.peopleCount); // <- logs: undefined
next(); // throws error: next is not a function
});
IDepartment
是我为部门文档创建的接口。
中间件确实被调用了,因为两个控制台都记录了日志,但this.peopleCount
的日志未定义,当它到达next()
时,会抛出next is not a function
的错误。
这是我的界面:
import { Document } from "mongoose";
interface IEmployeeInput {
departmentId: string;
employeeSkills: {
primaryIDs: string;
secondaryIDs: string[];
};
egn: string;
firstName: string;
lastName: string;
middleName: string;
}
export interface IEmployee extends IEmployeeInput, Document {
internalCompanyId: string;
fullName: string;
createdAt: Date;
updatedAt: Date;
schedule: number;
}
模式:
import { model, models, Schema, HookNextFunction } from "mongoose";
import { IDepartment } from "~/types";
const schema = new Schema<Required<IDepartment>>({
initials: { length: 4, type: String },
name: { maxlength: 20, minlength: 4, required: true, type: String, unique: true },
peopleCount: { type: Number, required: true },
});
schema.pre("updateOne", function (this: IDepartment, next: HookNextFunction) {
console.log("pre update department");
console.log(this.peopleCount);
next();
});
export const DepartmentModel = models.Department || model<IDepartment>("Department", schema);
在处理由schema.pre
调用分配的updateOne和deleteOne中间件时有一个特定的怪癖:
与
schema.pre('remove')
不同,Mongoose注册updateOne
和Query#updateOne()
和Query#deleteOne()
上的deleteOne
中间件违约这意味着doc.updateOne()
和Model.updateOne()
触发器updateOne
挂起,但this
指的是查询,而不是文档。
您需要修改中间件注册代码,以强制将其分配给Document:
schema.pre('updateOne',
{ document: true, query: false },
function() { ... });