【问题标题】:TypeError:Cannot read property 'id' of undefined - nodejs - SequlizeTypeError:无法读取未定义的属性'id' - 节点js - Sequelize
【发布时间】:2017-12-20 12:25:51
【问题描述】:

我正在尝试将多行保存到数据库中,但一直收到此错误:

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);                        
                }                
            }

数据库插入操作级别:

 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}});
      }

有什么想法吗?

--------编辑-----

我得到一些奇怪的行为: 该过程 - 在 testBulkInsert 中 - 也执行“then”和“catch”分支。第一次保存 - 真的,对象出现在数据库中 - 元素,在它移动到 catch 分支并抛出这个错误之后......我没有在工作流中调用这个方法两次......

【问题讨论】:

  • 您能否给我们一些详细信息,例如:错误发生在哪里?哪一行?
  • 看来问题出在“result.res = obj;”可能“obj”未定义然后“module.list.push(result.res[i].id);”触发错误
  • @Toodoo 错误在 testBulkInsert 操作中被抛出。 “TypeError: Cannot read property 'id' of undefined”这一行来自这里:“console.log('Error during create new row...', err);”

标签: javascript node.js sequelize.js bulkinsert


【解决方案1】:

我明白了:只需删除 createsomething 方法中的 for 循环 - 这个模型不需要那个过程 - 实际上我在代码中的 if 语句中也有一些错误,什么是也不在这里引用。我修复了这些,并且代码运行良好。 :)

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 2018-11-30
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多