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

标签 node.js postgresql sequelize.js

我在 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/

相关文章:

printf - node.js 是否有 sprintf 等价物

postgresql - 不支持的前端协议(protocol) 1234.5680 : server supports 2. 0 到 3.0

mysql - 序列化从创建和减量读取数据

postgresql - 使用 Sequelize.js 在 Postgresql 中保存对象数组

sqlite - Sequelize 生成的列 sqlite

javascript - jsdom:运行页面的 javascript 函数

node.js - 通过 nginx 1.10.3 和 LetsEncrypt 保护 WebSocket 连接

sql - 插入 COALESCE(NULL,default)

postgresql - 在 k8s/Skaffold 中为 Postgres 容器映射本地卷和端口绑定(bind)

javascript - 如何计算元素总金额