我在一个函数中有两个数据库Mutations .我可以想象第一个Mutations 成功,第二个Mutations 失败的情景.第一个改变了一些东西,第二个失败了.我能以某种方式取消第一个Mutations 吗?

export const postReset = async (req, res, next) => {
  const cardId = req.body.cardId;
  const userId = req.user?.id;

  if (!cardId || !userId) {
    return res.status(404).json({
      success: false,
    });
  }
  try {
    // First mutation
    const cardRemoved = await UsersModel.updateOne(
      { _id: userId },
      { $pull: { cards: { cardId: cardId } } },
      { safe: true, multi: true }
    );

    if (!cardRemoved) {
      return res.status(404).json({
        success: false,
      });
    }
  } catch (error) {
    return res.status(404).json({
      success: false,
    });
  }
  try {
    // Second mutation
    const cardRemovedFromCardsColelction = await CardsModel.findOneAndDelete({
      cardId: cardId,
      cardOwner: userId,
    });
    if (!cardRemovedFromCardsColelction) {
      return res.status(404).json({
        success: false,
      });
    }
    return res.status(201).json({
      success: true,
    });
  } catch (error) {
    return res.status(404).json({
      success: false,
    });
  }
};

推荐答案

这两个查询必须是单个事务的一部分.然后,如果事务中的执行因任何原因而失败-预期的更改将不会持久保存在数据库中.

基本的例子是:

const doc = new Person({ name: 'Will Riker' });

await db.transaction(async function setRank(session) {
  doc.name = 'Captain';
  await doc.save({ session });

  // Throw an error to abort the transaction
  throw new Error('Oops!');
}).catch(() => {}); // doc wasn't saved in the end

有关与Mongoose进行交易的更多细节和解释,请参见here.

Node.js相关问答推荐

如何处理EPIPE时,使用axios并期待413响应?

DocuSign:调用createEntaine时,RequestJWTApplicationToken返回401 AUTHORIZATION_INVALID_TOKEN

购物车是空的状态|本地存储不更新产品数量|Redux|

如何修复PostgreSQL和NodeJS/NestJS应用程序之间的日期时间和时区问题?

如何在医学中按patientId查找一个并同时插入多个数据

向url传递多个参数

为什么 mongoose 没有常规数组方法

使用 Node.js 在 MongoDB 中搜索

我怎样才能让`git`失败而不是要求提供凭据

如何使动态私有IP地址静态?

如何在 node.js 环境中从 WebAssembly (Rust) 调用异步 JavaScript 导入函数?

node.js 中 res.setHeader 和 res.header 的区别

在 Node.js 中的两个不同进程之间进行通信

如何让should.be.false语法通过 jslint?

代理后面的凉亭

如何使用 Node.js、Express 和 Mongoose 进行身份验证?

安装 node 包时可以使用自定义目录名称而不是node_modules吗?

路由后的 Node Express 4 中间件

在 Node.js 中混合使用 JavaScript 和 TypeScript

AWS Lambda:如何将秘密存储到外部 API?