MongoError: WriteConflict

Viewed 1919

When i send multi request from frontend (react) to backend (nodejs) simultaneously, the server gives me this error MongoError: WriteConflict. i am using transaction when i want to update some data in database:

code:

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)
        );
      }

all things works fine but when i want to send multi request (just for testing) the server throw this error.

1 Answers
Related