Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled rejection SequelizeDatabaseError: relation "users" does not exist

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?
like image 423
AG_HIHI Avatar asked Jul 10 '18 14:07

AG_HIHI


1 Answers

This problem occurs because creating a table is an asynchronous function. The problem is, the findAll() function can get executed while the table has not been created. to solve this, you can use:


(async ()=>{
    await User.sync({force: true});
    // Table created
    await User.create({
      firstName: 'John',
      lastName: 'Hancock'
    });
    const users=await User.findAll();
    console.log(users);

})();



like image 103
daffa fathani adila Avatar answered Sep 26 '22 05:09

daffa fathani adila