Why is db.findAll() is not a function?

I create and instance of database with sequelize, but it does not have methods like findAll(). What am i doing wrong?

const Sequelize = require('sequelize');
const router = require('express').Router();

const db = new Sequelize('web-prog', 'postgres', '1234', {
    host: 'localhost',
    dialect: 'postgres',
    logging: false
});

router.get('/', (req, res) => {
    db
        .findAll()
        .then(itemlist => res.json(itemlist))
        .catch(err => console.log(err))
});

module.exports = { db, router };

//then i require it like this

const db = require('./database').db;

TypeError: db.findAll is not a function

Upvotes: 0

Views: 765

Answers (1)

doublesharp
doublesharp

Reputation: 27599

You are trying to call findAll() on the Sequelize connection, however this method is found on the Model which is why you are getting the error.

Create a Model called MyModel

module.exports = function Model(db, DataTypes) {
  const MyModel = db.define('myModel', {/* fields */, {/* options */});
  return MyModel;
}

Then you would load the models -

  const db = require('./database').db;
  const myModel = db.import(path.join(__dirname, '/', 'myModel'));
  myModel.findAll() <-- this will exist and return a promise

Upvotes: 2

Related Questions