【问题标题】:MongoError: WriteConflictMongoError:写冲突
【发布时间】:2020-12-06 18:27:21
【问题描述】:

当我同时从前端 (react) 向后端 (nodejs) 发送多个请求时,服务器给了我这个错误 MongoError: WriteConflict。当我想更新数据库中的一些数据时,我正在使用transaction

代码:

const db = require("../../utils/database-connection/database");
const FollowersFollowing = require("../../models/followers-following/followers-following-models");

  const session = db.client().startSession();
  session.startTransaction();

      let whoFollowed;

      try {
        whoFollowed = await FollowersFollowing.updateFollow(
          userId,
          targetUserId,
          { session },
          "follow"
        );

        await Notice.updateNotice(
          userId,
          targetUserId,
          { session },
          "showUserOnTargetUserNotice"
        );

        await session.commitTransaction();
        session.endSession();
      } catch (error) {
        console.log(error);
        await session.abortTransaction();

        return next(
          new HttpError("could not follow the user, please try again.", 500)
        );
      }

一切正常,但是当我想发送多个请求(仅用于测试)时,服务器会抛出此错误。

【问题讨论】:

    标签: node.js mongodb transactions


    【解决方案1】:

    请参阅https://docs.mongodb.com/manual/core/transactions/ 了解正确的使用模式。您必须重试 withTransaction 助手为您执行的错误。

    【讨论】:

    猜你喜欢
    • 2015-07-07
    • 2015-07-14
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    相关资源
    最近更新 更多