user938363
user938363

Reputation: 10378

How to create database table from sequelizejs model definition?

There are several models defined with sequelizejs for my nodejs project. Here is an example of Event model in event.js:

const Event = db.define('event', {
    id: {type: Sql.INTEGER,
         primaryKey:true,
         min: 1},
    name: {type: Sql.STRING,
           min:2,
           allowNull: false,
        }, 
    event_info: {type: Sql.JSON},
    current_step: {type: Sql.STRING},
    customer_id: {type: Sql.INTEGER},
    access_list: {type: Sql.JSON},
    event_snapshot: {type: Sql.JSON},
    event_category_id: {type: Sql.INTEGER,
            },
    status: {type: Sql.STRING,
             isIn: ['active', 'cancelled', 'aborted', 'completed']},
    last_updated_by_id: {type: Sql.INTEGER},
    createdAt: Sql.DATE,
    updatedAt: Sql.DATE
}); 

Is there a way I can create the event table out of the event.js in command line?

Upvotes: 2

Views: 1723

Answers (2)

slysterous
slysterous

Reputation: 134

You could do it as @Chase mentioned but in my humble opinion, you should have split files for models and migrations.

This way you will have your current state of models represented in the model files (like the one you have) and the historical state of your database in Migration files.

Syncing will always drop any tables that exist and create them from scratch using the models. The mentioned solution will indeed create the table or update it (thought it will be doing a drop and then a create) but you will lose all data in the process. Migrations are generally preferred.

Upvotes: 3

Chase
Chase

Reputation: 3105

You could, if you instantiate Sequelize and call sync in your event.js script as well.

Upvotes: 2

Related Questions