5

I am a newby with Sequelize and Node.js in general, I am wondering if .sync() is ever needed for anything else than creating and structuring a database to fit exactly with your project in the development phase.

Take the following example: If I already have my database structure (made with MySQL Workbench or whatever), is it useful somehow to ever use .sync()? Does it have any important application in production?

UserJ
  • 159
  • 3
  • 13
  • @AbhinavD covered it but to re-iterate: `sync` would never be used on a real database. You should only use migrations. However, `sync` is incredibly valuable for testing! It's an easy way to ensure your test suites are run against a clean database. – mcranston18 May 16 '18 at 15:12
  • Good point @mcranston18. We mostly run our migrations `down` and then `up` before running our tests. This gives us the advantage to make sure our `down` migrations are working right as well. In case, we have to roll back on production, this comes really handy – AbhinavD May 17 '18 at 09:15

2 Answers2

7

If I already have my database structure (made with MySQL Workbench or whatever), is it useful somehow to ever use .sync()? Does it have any important application in production?

No. Sequelize sync will create tables that do not exists. If you already have all the tables, it will not do anything. However if you use force: true, it will drop the table that exists and recreate them from the model definition.

On a separate note, one should prefer migrations over sync. sync does not reflect tale alterations. Migrations are more powerful, you can undo, redo and much more with it.

Here is a good answer on Sequelize.js: how to use migrations and sync

AbhinavD
  • 6,892
  • 5
  • 30
  • 40
0

sequelize.sync() creates tables for all models that were defined (i.e., using the define method on an instance of Sequelize). It syncs models to the database by creating the appropriate tables, and if applicable, relations.

Example:

sequelize
  .sync()
  .then(result => {
    console.log(result);
  })
  .catch(err => console.log(err));

This is what was at the beginning of the console log (the 'products' table was created based on the 'product' model; it's automatically pluralized):

Executing (default): CREATE TABLE IF NOT EXISTS `products` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `price` DOUBLE PRECISION NOT NULL, `imageUrl` VARCHAR(255) NOT NULL, `description` VARCHAR(255) NOT NULL, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
nCardot
  • 5,992
  • 6
  • 47
  • 83