抛出:参考错误: 未定义"/>
为什么我的knex事务抛出:参考错误: 未定义
我正在使用交易方法完成我的第一个knex交易。目的是使三个插入语句的集合以原子方式将传入记录的数据持久保存到三个表中。对于上下文-传入的记录代表具有两个1:M子关系的父对象-“材料具有0到许多属性,而材料具有0到许多音符。”所以我有一个材料关系,一个material_properties关系和一个material_notes关系。
我有一个不在事务内的方法版本。但是,当我尝试在Knex documentation - 'Transaction' section中指定的事务中包装功能时,在“与上述示例相同,使用另一种await / async方法:”小节中,我收到一个参考错误,即第一个子关系不是定义。另外,我得到一个
UnhandledPromiseRejectionWarning:ReferenceError:未定义trx
注意:父表被插入到第一个表中,并且尝试插入第一个子表时出现参考错误:'material_properties'。
这是有效的方法:
const materialRecord = {
name: material.name,
description: material.description ? material.description : null,
user_id: userId
}
/**
* Insert primary material into materials & get id value for FK
*/
const materialPrimaryKeyArray = await knex('materials')
.returning('id')
.insert(materialRecord)
.catch(error => console.error(`Unable to persist record, ${error}`))
const materialPrimaryKey = materialPrimaryKeyArray[0];
/**
* Persist properties and/or notes if they exist
*/
if (material.materialProperties) {
material.materialProperties.forEach(property => {
property['material_id'] = materialPrimaryKey
});
knex('material_properties')
.returning('id')
.insert(material.materialProperties)
.catch(error => console.error(`Unable to persist record, ${error}`))
};
if (material.materialNotes) {
material.materialNotes.forEach(note => {
note['material_id'] = materialPrimaryKey
});
knex('material_notes')
.returning('id')
.insert(material.materialNotes)
.catch(error => console.error(`Unable to persist record, ${error}`))
};
return materialPrimaryKey;
回答如下:您正在尝试访问其范围之外的trx
变量。
} catch (error) {
console.error(`Unable to persist data, ${error}`)
trx.rollback // here you are trying to use undefined variable
}
您可以删除该行。由于knex.transaction(async trx => {})
引发错误,因此交易会自动回滚(因为处理程序功能正在重新调整承诺)。
也只访问函数而不调用它trx.rollback
和trx.rollback()
不会做任何事情。
更多推荐
为什么我的knex事务抛出:参考错误: 未定义
本文发布于:2024-05-07 04:52:34,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
- 上一篇: 织梦某处设计缺陷导致后台地址泄露
- 下一篇: 谁来结束GUI程序
发布评论