gpt4 book ai didi

node.js - 如何防止 Sequelize 使用 Postgres 为主键插入 NULL

转载 作者:IT老高 更新时间:2023-10-28 23:18:38 27 4
gpt4 key购买 nike

我在 postgresql 9 中创建了一个表

create table stillbirth(id serial primary key, state varchar(100), count int not null, year int not null); 

尝试使用 sequelize 1.4.1 版本在 node.js 上编写示例。

将上表映射为

var StillBirth = sequelize.define('stillbirth',
{ id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
state: Sequelize.STRING,
year: Sequelize.INTEGER,
count: Sequelize.INTEGER
}, {timestamps: false, freezeTableName: true});

现在当我尝试创建一个死胎的新实例并保存它时,我得到了错误。

/** 新实例创建代码**/

StillBirth
.build({state: objs[j].state, year: objs[j].year, count: objs[j].count})
.save()
.error(function(row){
console.log('could not save the row ' + JSON.stringify(row));
})
.success(function(row){
console.log('successfully saved ' + JSON.stringify(row));
})

我得到的错误

*执行:INSERT INTO "stillbirth"("state","year","count","id") VALUES ('Andhra Pradesh',2004,11,NULL) RETURNING ;无法保存行 {"length":110,"name":"error","severity":"ERROR","code":"23502","file":"execMain.c","line": "1359","例程":"ExecConstraints"}

如果您查看它生成的 sql,它会将空值作为主键,理想情况下应该由 db 生成。

有人可以帮我看看我在这里缺少什么吗?

最佳答案

您必须使用名为 omitNull 的特殊标志来实例化 Sequelize:

var sequelize = new Sequelize('db', 'user', 'pw', {
omitNull: true
})

这将禁止将未定义的值插入为NULLhttp://sequelizejs.com/#usage-options

您可能需要更新到 v1.5.x 或 1.6.0-betaX

关于node.js - 如何防止 Sequelize 使用 Postgres 为主键插入 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14332376/

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