在猫鼬中间件中"this"和"next",TS 不起作用



我正在尝试让中间件使用Typescript,但prepost中的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注册updateOneQuery#updateOne()Query#deleteOne()上的deleteOne中间件违约这意味着doc.updateOne()Model.updateOne()触发器updateOne挂起,但this指的是查询,而不是文档。

您需要修改中间件注册代码,以强制将其分配给Document:

schema.pre('updateOne', 
{ document: true, query: false }, 
function() { ... });

最新更新