I tried to configure Sequelize for TS according to the guide, but I can’t solve the problem. The connection to the database is active, but I can't solve the problem with the type:
` TSError: ⨯ 无法编译 TypeScript: controller/todo.controller.ts:7:46 - 错误 TS2339:类型“typeof Todo”上不存在属性“findAll”。
const todos: Promise<any> = await Todo.findAll()`
class Todo extends Model<InferAttributes<Todo>, InferCreationAttributes<Todo>>{
declare id: CreationOptional<number>;
declare todo: string;
declare status: string;
}
Todo.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
//other fields
}, {
sequelize,
tableName: 'todos',
});
export default Todo
export const getAllTodos = async (req: Request, res: Response) => {
try {
const todos = await Todo.findAll()
} catch (e) {
console.log(e);
}
};
I tried to do it following the official documentation https://sequelize.org/docs/v6/other-topics/typescript/ and guides on the Internet If anyone knows how to solve it, please help!
文档向您展示了它如何在一个文件中工作,但在实际项目中,您需要将模型分离到不同的文件中,并且它们的逻辑也将位于单独的文件中。
您需要连接到sequelize,然后像这样在入口点文件中注册模型
// app.js
setupSequelize(app);
registerModels(app);
寄存器模型文件应该是这样的
// models/index.js
const createTodoModel = require('./todo.model');
function getModel(modelName) {
const sequelize = this.get('sequelizeClient');
return sequelize.models[modelName];
}
module.exports = function registerModels(app) {
createTodoModel(app);
const sequelize = app.get('sequelizeClient');
const { models } = sequelize;
Object.keys(models).forEach(name => {
if ('associate' in models[name]) {
models[name].associate(models);
}
});
app.getModel = getModel;
}
然后在你的待办事项中你需要这样做
export const getAllTodos = async (req: Request, res: Response) => {
const TodoModel = app.getModel('TodoModel');
try {
const todos = await TodoModel.findAll()
} catch (e) {
console.log(e);
}
};
有关整个流程以及如何配置sequelize在您的项目中工作以及如何管理模型之间的关系避免循环依赖问题的更多信息,请检查此repository和sequelize setup的实现,您也可以从这里
检查如何创建模型