使用 MongoDB 事务的要求 [英] Requirements for using MongoDB transactions

查看:278
本文介绍了使用 MongoDB 事务的要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建新票证时,我尝试使用 mongo 事务,以便在保存票证过程"或发布票证创建事件"中的至少一个失败时回滚事务.

When creating a new ticket I am trying to use mongo transactions so that I could rollback the transaction if at least one of the "ticket saving process" or "Publishing the ticket created event" fails.

在 try catch 块中,我手动抛出了错误(throw new Error('ssomlk造成了手动错误');),所以我可以尝试测试事务是否有效.

Inside the try catch block I have manually thrown the error (throw new Error('ssomlk caused manual error');) so I could try to test whether the transaction works.

const session = await mongoose.startSession();
session.startTransaction();
try {
  await ticket.save({ session });
  throw new Error('ssomlk caused manual error');
  await new TicketCreatedPublisher(natsWrapper.client).publish({
    id: ticket.id,
    title: ticket.title,
    price: ticket.price,
    createdBy: ticket.createdBy,
  });
  await session.commitTransaction();
  session.endSession();
  res.status(201).send(ticket);
} catch (error) {
  session.abortTransaction();
  session.endSession();
  console.log(error);
  res.status(401).send({ error: error.message });
}

但我收到以下错误

MongoError:此 MongoDB 部署不支持可重试写入.请将 retryWrites=false 添加到您的连接字符串中.

MongoError: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.

根据 stackoverflow 的回答,我在 mongo URI 中包含了?retryWrites=false",但仍然没有运气.

According to stackoverflow answers I have included "?retryWrites=false" to my mongo URI but still no luck.

任何建议都会有很大帮助

Any advise would be of great help

推荐答案

首先,您应该使用描述的模式 此处(点击 nodejs 查看节点示例).

First, you should be using the pattern described here (click on nodejs to see the node examples).

其次,交易需要:

  • WiredTiger 存储引擎
  • 副本集(服务器 4.0+)或分片集群(服务器 4.2+)

在 4.0 和独立服务器上使用 mmapv1 存储引擎的部署不支持事务.

Deployments using mmapv1 storage engine on 4.0 and standalone servers do not support transactions.

这篇关于使用 MongoDB 事务的要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆