nestjs/mongoose

Documents are still added even when the abortTransaction was called

Closed this issue · 2 comments

I managed to add transaction using @InjectConnection decorator from @nestjs/mongoose library and injecting the dependency in the service constructor but one of the two documents was added even when there was an error.

My code of AuthService class:

import {InjectConnection} from '@nestjs/mongoose';
import * as mongoose from 'mongoose';

export class AuthService {
constructor(
    private readonly userService: UserService,
    private readonly profileService: ProfileService
    @InjectConnection() private readonly connection: mongoose.Connection){}

The account creation function in AuthService

const transactionSession = await this.connection.startSession();
    transactionSession.startTransaction();

    try
    {
      const newSignupBody: CreateUserDto = {password: hashedPassword, email, username};
  
      const user: User = await this.userService.create(newSignupBody);

      //save the profile.
      const profile: Profile = await this.profileService.create(user['Id'], signupDto);

      const result:AuthResponseDto = this.getAuthUserResponse(user, profile);

      transactionSession.commitTransaction();
      return result;
    }
    catch(err)
    {
      //here it should abort the request because profile service return an error
      transactionSession.abortTransaction();
      throw new CustomErrorHandler(err)
    }
    finally
    {
      transactionSession.endSession();
    }

Following the mongoose documentation, it works in expressjs using the mongoose itself to initiate a transa tion.

But if we try to use mongoose directly in nestjs, it returns connection error referred to: https://stackoverflow.com/questions/67879357/nestjs-how-to-use-mongoose-to-start-a-session-for-transaction.

I resolved the connection issue by using nestjs/mongoose connection object.

But here, it is not aborting the transaction. The documents are still being added

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.