Unhandled rejection SequelizeDatabaseError: relation "users" does not exist

Ahmed Ghrib picture Ahmed Ghrib · Jul 10, 2018 · Viewed 24k times · Source

I am getting started with Sequelize. I am following the documentation they are providing on their website :http://docs.sequelizejs.com/manual/installation/getting-started.html

const Sequelize = require('sequelize');
const sequelize = new Sequelize('haha', 'postgres', 'postgres', {
  host: 'localhost',
  dialect: 'postgres',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite'
});


sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


  const User = sequelize.define('user', {
    firstName: {
      type: Sequelize.STRING
    },
    lastName: {
      type: Sequelize.STRING
    }
  });

  // force: true will drop the table if it already exists
  User.sync({force: true}).then(() => {
    // Table created
    return User.create({
      firstName: 'John',
      lastName: 'Hancock'
    });
  });

Up until here, everything works perfectly. And the table "user" is correctly built and populated. (Although I do not understand Sequelize appends an "s" automatically to "user", any explanation.)

enter image description here

enter image description here

However when I add the following portion of code:

User.findAll().then(users => {
  console.log(users)
})

I get this error :

Unhandled rejection SequelizeDatabaseError: relation "users" does not exist

So my questions are:

  1. Why does Sequelize add an "s" to user. (I know it makes sense but shouldn't the developer decide that)
  2. What is causing that error? I followed the documentation but it still didn't work?

Answer

ccordon picture ccordon · Dec 28, 2018

When you are defining your model you can add configurations, in this case the option that you must add is freezeTableName prevents the names from being plural.

const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING
  },
  lastName: {
    type: Sequelize.STRING
  }
}, {
    // disable the modification of table names; By default, sequelize will automatically
    // transform all passed model names (first parameter of define) into plural.
    // if you don't want that, set the following
    freezeTableName: true,
  });