gpt4 book ai didi

node.js - 初次使用 Sequelize js 避免出现空表行。

转载 作者:行者123 更新时间:2023-11-29 13:13:54 26 4
gpt4 key购买 nike

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

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

最佳答案

只是改变

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

关于node.js - 初次使用 Sequelize js 避免出现空表行。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com