Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Sync vs Migrations

Im learning Sequelize and I'd like some clarification around syncing vs migrations.

I understand that sync will create missing tables based on my model schema but I have also read that sync is meant for initializing the database whereas migrations are meant for production.

If that is the case, the express-example shows calling sync from bin/www. Is that something that should not be used in production?

As an extension of this, if I am not to use sync in production, how do you apply model associations? Do I need to add them to migrations manually?

Essentially I am asking for an explanation of how these two concepts are meant to work together.

Thanks

like image 851
adampetrie Avatar asked Jan 11 '17 16:01

adampetrie


People also ask

What does Sequelize sync () do?

The Sequelize instance method sync() is used to synchronize your Sequelize model with your database tables. The synchronization happens at the table level. When your table doesn't exist the sync() method will generate and run a CREATE TABLE statement for you.

What are migrations in Sequelize?

A Migration in Sequelize is a javascript file which exports two functions, up and down , that dictates how to perform the migration and undo it. You define those functions manually, but you don't call them manually; they will be called automatically by the CLI.

How do I sync all models in Sequelize?

A model can be synchronized with the database by calling model.sync(options) , an asynchronous function (that returns a Promise). With this call, Sequelize will automatically perform an SQL query to the database. Note that this changes only the table in the database, not the model in the JavaScript side.


1 Answers

I recommend using sequelize migrations in development and production so that you are fully acclimate with the process which will give safe results, also sequelize sync without force will only create new tables with the specified schema which are not present in database, it wont reflect alterations in existing table schema. Sequelize migrations will help you update your database in a systematic and incremental manner.

Refer this page for more on this.

Sequelize.js: how to use migrations and sync

http://corpus.hubwiz.com/2/node.js/21105748.html

like image 82
Keval Gohil Avatar answered Sep 20 '22 13:09

Keval Gohil