Search code examples
mongodbmongoosetransactionses6-promise

need to create a mongoose transaction wrapper which will pass session as parameter to functions that actually do query operations to create or update


So lets say i have a function that takes care of user creation which was previously available to us. Now we just want the function to work in the form of one transaction that creates all users together if success or fails completely when it encounters any error. I am assuming passing just the session to the existing function from the transaction wrapper should take care of this. Any number of such function can be passed together and the wrapper should handle them all as a single transaction.

 const createUsers = async (users = []) => {
  try {
    return UserModel.create(users).then((res) => {
      logger.info(`[Start-Up] Created ${res.length} users`);
    }, (rej) => {
      logger.error(`[Start-Up] Failed to create users - ${rej}`);
      throw new Error(rej);
    });
  } catch (err) {
    throw new Error('Failed to create Users', err);
  }
};

Solution

  • Use https://www.npmjs.com/package/mongoose-transactions


    https://mongoosejs.com/docs/transactions.html

    const createUsers = async (users = []) => {
      const session = await UserModel.startSession();
      try {
        await session.withTransaction(() => {
            return UserModel.create(users, { session: session }).then((res) => {
              logger.info(`[Start-Up] Created ${res.length} users`);
            }, (rej) => {
              logger.error(`[Start-Up] Failed to create users - ${rej}`);
              throw new Error(rej);
            });
        });
      } catch (err) {
        throw new Error('Failed to create Users', err);
      } finally {
         session.endSession();
      }
    };