Sequelize error TS2339: Property 'findAll' does not exist

29 Views Asked by At

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: ⨯ Unable to compile TypeScript: controller/todo.controller.ts:7:46 - error TS2339: Property 'findAll' does not exist on type 'typeof Todo'.

const todos: Promise = 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!

1

There are 1 best solutions below

0
Mohamed Kamel On

The documentation shows you how it works in one file, but in a real-life project you will need to separate the models in different files and their logic will be in separate files as well.

You need to connect to sequelize and then register the models in your entry point file like that

// app.js

setupSequelize(app);
registerModels(app);

The register models file should be like that

// 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;
}

Then in your Todo you will need to do that

export const getAllTodos = async (req: Request, res: Response) => {
  const TodoModel = app.getModel('TodoModel');

  try {
    const todos = await TodoModel.findAll()
  } catch (e) {
    console.log(e);
  }
};

For more information about the whole flow and how to configure sequelize to work in your project and how to manage the relations among the models avoiding the circular dependency issues please check this repository and the implementation of sequelize setup, also you can check how to create a model from here