2

My initialize function keep re-creating tables and inserting empty row at every time I start my server. How do I avoid this persistency? I want my table created once and ensure that I can connected to the DB and that our Employee and Department models are represented in the database as tables using the initialize function.

const Sequelize = require("sequelize");

var sequelize = new Sequelize("***database**", "**user**", "**password**", {
    host: "ec2-54-227-240-7.compute-1.amazonaws.com",
    dialect: "postgres",
    port: 5432,
    dialectOptions: {
        ssl: true
    }
});

var Employee = sequelize.define('Employee', {
    employeeNum: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    firstName: Sequelize.STRING,
    lastName: Sequelize.STRING,
    email: Sequelize.STRING,
    SSN: Sequelize.STRING,
    addressStreet: Sequelize.STRING,
    addressCity: Sequelize.STRING,
    addressState: Sequelize.STRING,
    addressPostal: Sequelize.STRING,
    maritalStatus: Sequelize.STRING,
    isManager: Sequelize.BOOLEAN,
    employeeManagerNum: Sequelize.INTEGER,
    status: Sequelize.STRING,
    department: Sequelize.INTEGER,
    hireDate: Sequelize.STRING
}, {
    createdAt: false, // disable createdAt
    updatedAt: false // disable updatedAt
});

var Department = sequelize.define('Department', {
    departmentId: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    departmentName: Sequelize.STRING
}, {
    createdAt: false, // disable createdAt
    updatedAt: false // disable updatedAt
});

function initialize() {
    return new Promise((resolve, reject) => {
        sequelize.sync({ force: true }).then(() => {
            Employee.create().then(function(employee) {
                resolve();
            }).catch(() => {
                reject("Unabale to sync the database");
            });

            Department.create().then(function(department) {
                resolve();
            }).catch(() => {
                reject("Unabale to sync the database");
            });
        });
    });
};

1 Answer 1

2

Just Change

sequelize.sync({ force: true }) //<--- This will force to drop table and recreate it

To

sequelize.sync({ force: false , alter : true })
// this will create table if not exists but not drop by force
// and alter will update the table 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.