【问题标题】:Avoiding empty table rows with initial usage of Sequelize js.避免在初始使用 Sequelize js 时出现空表行。
【发布时间】:2019-01-03 01:59:20
【问题描述】:

每次启动服务器时,我的初始化函数都会重新创建表并插入空行。如何避免这种持久性?我希望我的表创建一次并确保我可以连接到数据库并 我们的 Employee 和 Department 模型在数据库中使用初始化函数表示为表。

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");
            });
        });
    });
};

【问题讨论】:

    标签: node.js postgresql heroku sequelize.js


    【解决方案1】:

    只是改变

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

    收件人

    sequelize.sync({ force: false , alter : true })
    // this will create table if not exists but not drop by force
    // and alter will update the table 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2019-08-27
      • 2019-08-30
      • 2012-07-09
      相关资源
      最近更新 更多