我在尝试使用Sequelize和Typescript时遇到以下错误,这两个我都还很陌生:
(node:17276) UnhandledPromiseRejectionWarning: TypeError: week.calculateDays is not a function
我的路线正在使用我的控制器中的以下内容:
import { Request, Response } from "express";
import models from "../models";
export class Weeks {
public static calculateDays = async (req: Request, res: Response) => {
console.log(req.params);
await models.Week.findByPk(req.params.id).then(week => {
if (week) {
console.log("Week found:", week);
week.calculateDays();
}
});
};
}
并在模型中定义了以下内容:
import Sequelize from "sequelize";
import { SequelizeAttributes } from "../typings/SequelizeAttributes";
import { WeekAttributes } from "../interfaces/attributes";
import { WeekInstance } from "../interfaces/instances";
import models from "../models";
import { SessionAttributes } from "./sessions";
export const WeekFactory = (
sequelize: Sequelize.Sequelize,
DataTypes: Sequelize.DataTypes
): Sequelize.Model<WeekInstance, WeekAttributes> => {
const attributes: SequelizeAttributes<WeekAttributes> = {
....attributes of the model....
};
const Week = sequelize.define<WeekInstance, WeekAttributes>(
"weeks",
attributes,
{
instanceMethods: {
calculateDays: async function (this: WeekInstance) {
console.log("Inside class method calculateDays");
return await calculateDays(this.id!);
}
}
}
);
const calculateDays = async (weekId: number) => {
.......
}
return Week;
};
我真的很感激任何方向,因为我不确定我在这里缺少什么。
答案 0 :(得分:0)
我认为问题在于您声明calculateDays
方法的方式。它不应该接受WeekInstance
参数,并且您可以在函数内部正常使用this
。另外,我建议不要对out函数calculateDays
使用相同的名称。我认为从实例方法内部无法访问它,并且有些混乱,因此我将其重命名为calculateDaysForWeek
instanceMethods: {
calculateDays: async function () {
console.log("Inside class method calculateDays");
return await calculateDaysForWeek(this.id!);
}
}
有关如何创建实例方法的良好参考:https://github.com/sequelize/sequelize/issues/9760