sequelize bulkCreate()返回主键的NULL值
我正在使用节点编写rest,作为ORM for mySQL的后缀。 我正在使用bulkCreate函数来批量创buildlogging。 但是作为响应,它为主键值返回null 。
模型
sequelize.define('category', { cat_id:{ type:DataTypes.INTEGER, field:'cat_id', primaryKey: true, autoIncrement: true, unique:true }, cat_name:{ type: DataTypes.STRING, field: 'cat_name', defaultValue:null } });
批量创build操作:
var data = [ { 'cat_name':'fashion' }, { 'cat_name':'food' } ]; orm.models.category.bulkCreate(data) .then(function(response){ res.json(response); }) .catch(function(error){ res.json(error); })
回应:
[ { "cat_id": null, "cat_name": "fashion", "created_at": "2016-01-29T07:39:50.000Z", "updated_at": "2016-01-29T07:39:50.000Z" }, { "cat_id": null, "cat_name": "food", "created_at": "2016-01-29T07:39:50.000Z", "updated_at": "2016-01-29T07:39:50.000Z" } ]
在MySQL中testing:
Model.bulkCreate(values, { individualHooks: true })
你应该设置returning
选项:
Model.bulkCreate(values, {returning: true})
var data = [ { 'cat_name':'fashion' }, { 'cat_name':'food' } ]; Model.bulkCreate(data) .then(function() { //(if you try to immediately return the Model after bulkCreate, the ids may all show up as 'null') return Model.findAll() }) .then(function(response){ res.json(response); }) .catch(function(error){ res.json(error); })
成功处理程序传递一个实例数组,但请注意这些可能不完全代表数据库中行的状态。 这是因为MySQL和SQLite不容易以一种可以映射到多个logging的方式获取自动生成的ID和其他默认值。 要获取新创build的值的实例,您需要再次查询它们。 http://docs.sequelizejs.com/en/latest/api/model/#bulkcreaterecords-options-promisearrayinstance
不幸的是,在最新版本中不起作用。 他们解释了为什么在这里: http : //sequelize.readthedocs.org/en/latest/api/model/#bulkcreaterecords-options-promisearrayinstance
注意这个描述具体提到mysql。 你将不得不查询他们。 (例子包括var _ = require('lodash');
var cat = rm.models.category; cat.bulkCreate(data) .then(function (instances) { var names = _.map(instances, function (inst) { return inst.cat_name; }); return cat.findAll({where: {cat_name: {$in: names}}); }) .then(function(response){ res.json(response); }) .catch(function(error){ res.json(error); });
- 书架(knex) – belongsToMany关系不工作
- Heroku和NodeJs – MySql连接丢失:服务器closures连接
- 如何查找没有joinWaterline ORM的logging
- TypeError:尝试将节点js连接到mysql以获取zendesk应用程序时,无法读取null属性的“createConnection”
- 如何使用node.js在mysql数据库上实现推送通知系统
- 用户注册使用护照+ express + mysql + sequelize
- Sequelize:错误:错误:Table 1没有关联到Table 2
- 将node-mysql结果行组合成node.js的单个JSON返回值
- Node.js mysql错误不能读取undefined的属性?