猫鼬的session.withTransaction
帮助器仅执行第一次写入。这是代码:
const session = await mongoose.startSession();
await session.withTransaction(async () => {
const member = await Member.create([{
name: 'John Doe'
email: 'johndoe@example.com',
}], { session });
await User.updateOne({ _id: req.user.id }, { member: member._id }, { session });
});
此代码在数据库中创建一个新成员,但不会更新用户。难道不是只有每个操作都成功的交易才有意义吗?我究竟做错了什么;还是用猫鼬是不可能的?
猫鼬:5.9.26, Node.js:14.9.0
答案 0 :(得分:0)
检查是否以您要基于交易的模型开始会话:
const session = await Member.startSession();
答案 1 :(得分:0)
// Cannot change committed transaction but allow retrying commitTransaction command.
uassert(ErrorCodes::TransactionCommitted,
str::stream() << "Transaction " << requestTxnNumber << " has been committed.",
cmdName == "commitTransaction" || !o().txnState.isCommitted());
很显然,您尝试两次提交事务。确保您不重复使用它。始终结束会话:
const session = await mongoose.startSession();
try {
await session.withTransaction(async () => {...})
} finally {
await session.endSession()
}
答案 2 :(得分:0)
你有没有尝试过这样写
{session :session }
答案 3 :(得分:0)
确保您有副本设置,事务需要副本才能工作。