我正在使用 Mongoose 访问我的数据库。我需要使用事务来进行原子插入更新。
95% 的时间我的交易运行良好,但 5% 的时间显示错误:
“给定的交易号 1 与任何正在进行的交易都不匹配”
重现这个错误非常困难,所以我真的很想了解它来自哪里以消除它。
我找不到关于这种行为的非常明确的解释。
我尝试在各种函数上使用 async/await 关键字。不知道是手术不及时还是太早了。
这是我正在使用的代码:
export const createMany = async function (req, res, next) {
if (!isIterable(req.body)) {
res.status(400).send('Wrong format of body')
return
}
if (req.body.length === 0) {
res.status(400).send('The body is well formed (an array) but empty')
return
}
const session = await mongoose.startSession()
session.startTransaction()
try {
const packageBundle = await Package.create(req.body, { session })
const options = []
for (const key in packageBundle) {
if (Object.prototype.hasOwnProperty.call(packageBundle, key)) {
options.push({
updateOne: {
filter: { _id: packageBundle[key].id },
update: {
$set: {
custom_id_string: 'CAB' + packageBundle[key].custom_id.toLocaleString('en-US', {
minimumIntegerDigits: 14,
useGrouping: false
})
},
upsert: true
}
}
})
}
}
await Package.bulkWrite(
options,
{ session }
)
for (const key in packageBundle) {
if (Object.prototype.hasOwnProperty.call(packageBundle, key)) {
packageBundle[key].custom_id_string = 'CAB' + packageBundle[key].custom_id.toLocaleString('en-US', {
minimumIntegerDigits: 14,
useGrouping: false
})
}
}
res.status(201).json(packageBundle)
await session.commitTransaction()
} catch (error) {
res.status(500).end()
await session.abortTransaction()
throw error
} finally {
session.endSession()
}
}
我希望我的代码添加到数据库中并以原子方式更新条目包,不存在不稳定的数据库状态。
这对于主要部分来说工作得很好,但我需要确保这个错误不再出现。