我正在尝试将多行保存到数据库中,但始终出现此错误:
TypeError: Cannot read property 'id' of undefined
以下是一些代码实现:
数据库插入调用级别:
createsomething(req, res, module, next){
//...
testQuery.testBulkInsert(model, persistable,
function(result){
if(result.error == ''){
for(i = 0; i < result.res.length; i++){
module.list.push(result.res[i].id);
}
next(module);
} else {
console.log('error #&@{;$÷');
console.log(result.error);
}
}
Db插入操作级别:
function testBulkInsert(model, values, next){
console.log(values);
model.bulkCreate(values)
.then(function(obj){
let result = new ResponseClass();
result.res = obj;
next(result);
})
.catch(function(err){
console.log('Error during create new row...', err);
let result = new ResponseClass();
result.error = 'Error during create new row...';
next(result);
});
}
响应类:
function SQLResponse(){
this.res = '';
this.error = '';
}
module.exports = SQLResponse;
在testBulkInsert函数中,console.log(values);结果很好,我得到了目标:
[
{
title: 'dfasfa',
url: 'fadfa',
someOtherModelId: 18
}, {
title: 'fds',
url: 'ghhgdj',
someOtherModelId: 18
}
]
和模型
var SomeModel= sequelize.define("SomeModel",
{
id : { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true, allowNull: false },
title : {type : DataTypes.STRING, allowNull: false },
url : {type : DataTypes.STRING, allowNull: false }
}
);
SomeModel.associate = function(models) {
SomeModel.belongsTo(models.someOtherModelId, {foreignKey: {name:'someOtherModelId', allowNull:false}});
}
有什么想法吗?
------ ------ EDIT
我得到一些奇怪的行为: 该过程 - 在testBulkInsert中 - 也执行“then”和“catch”分支。第一次它保存 - 实际上,对象出现在db - 元素中,然后它进入catch分支并抛出此错误......我没有在工作流中两次调用此方法....
答案 0 :(得分:0)
我明白了一点:只需删除createsomething方法中的for循环 - 这个模型不需要那个过程 - 实际上我在代码中的 if 语句中也有一些错误,什么也不是这里引用。我修复了这些,代码运行良好。 :)