The mongoose documentation to use a transaction is straightforward but when it is followed in nestjs, it returns an error:
Connection 0 was disconnected when calling `startSession`
MongooseError: Connection 0 was disconnected when calling `startSession`
at NativeConnection.startSession
My code:
const transactionSession = await mongoose.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)
{
transactionSession.abortTransaction();
}
finally
{
transactionSession.endSession();
}
I found the solution after studying @nestjs/mongoose. The mongoose here has no connection in it. This is the reason of error being returned.
The solution:
import {InjectConnection} from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
In the constructor of the service class, we need add connection parameter that can be used by the service.
export class AuthService {
constructor(
// other dependencies...
@InjectConnection() private readonly connection: mongoose.Connection){}
Instead of
const transactionSession = await mongoose.startSession();
transactionSession.startTransaction();
We will now use:
const transactionSession = await this.connection.startSession();
transactionSession.startTransaction();
This way, the issue of disconnection after startSession() can be resolved.