Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize table name change

Tags:

sequelize.js

Have renamed a table from users to user in MySQL database. In Express I'm running Sequelize and created a schema for the old users table. With the table renamed and everything in the code changed from users to user, Sequelize is still looking for a table named specifically users even though the table name is updated in the schema.

User = db.sequelize.define('user', {
  first_name: Sequelize.STRING,
  last_name: Sequelize.STRING,
  email: Sequelize.STRING,
  password: Sequelize.STRING,
  role: Sequelize.STRING,
  created_at: Sequelize.DATE,
  updated_at: Sequelize.DATE
});

Tried running this to overwrite the table with one produced by Sequelize and it still created a table named users

User.sync({force: true}).then(() => {
  // Table created
  return User.create({
    firstName: 'test',
    lastName: 'test',
    email: '[email protected]',
    password: 'password'
  });
});

Has anyone else experienced the same? Is there some other configuration I am missing? This is all I did in the first place when creating the first table.

like image 659
anaximander Avatar asked Apr 17 '18 19:04

anaximander


3 Answers

Sequelize pluralizes table name by default, Set freezeTableName: true to change this behavior like this.

User = db.sequelize.define('user', {
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING,
    email: Sequelize.STRING,
    password: Sequelize.STRING,
    role: Sequelize.STRING,
    created_at: Sequelize.DATE,
    updated_at: Sequelize.DATE
}, {
    freezeTableName: true
});
like image 155
Mansoor Ul Haq Avatar answered Oct 15 '22 16:10

Mansoor Ul Haq


Its been years since I've used the Sequelize framework, but I'm pretty sure the framework has a concept of pluralized table names by default. From memory, configuration needs to be provided in create to prevent this - so in conjunction with your non-pluralized table name, you'd also specify freezeTableName: true.

Looks like the docs state this:

http://docs.sequelizejs.com/manual/tutorial/models-definition.html#configuration

like image 40
Dacre Denny Avatar answered Oct 15 '22 16:10

Dacre Denny


recent sequelize version allows you to do this

up: async (queryInterface, Sequelize) => queryInterface.showAllTables().then(async (tables) => {any function})
like image 37
OLUWATOSIN.A AKINYELE Avatar answered Oct 15 '22 16:10

OLUWATOSIN.A AKINYELE