如何防止Sequelize使用Postgres为主键插入NULL

ani*_*hek 10 postgresql node.js sequelize.js

我在postgresql 9中创建了一个表

create table stillbirth(id serial primary key, state varchar(100), count int not null, year int not null); 
Run Code Online (Sandbox Code Playgroud)

尝试使用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});
Run Code Online (Sandbox Code Playgroud)

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

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

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));
   })
Run Code Online (Sandbox Code Playgroud)

我得到的错误

*执行:INSERT INTO"死产"("州","年","计数","id")价值('Andhra Pradesh',2004,11,NULL)返回; 无法保存行{"length":110,"name":"error","severity":"ERROR","code":"23502","file":"execMain.c","line": "1359", "程序": "ExecConstraints"}

如果你查看它生成的sql,它会为主键设置null,理想情况下应该由db生成.

有人可以帮助我,我在这里缺少什么?

sde*_*old 18

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

var sequelize = new Sequelize('db', 'user', 'pw', {
  omitNull: true
})
Run Code Online (Sandbox Code Playgroud)

这会disable inserting undefined values as NULL.http://sequelizejs.com/#usage-options

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