Nestjs:如何使用猫鼬启动交易会话?

Nestjs: How to use mongoose to start a session for transaction?

使用事务的 mongoose 文档很简单,但是在 nestjs 中遵循它时,returns 出现错误:

Connection 0 was disconnected when calling `startSession`
MongooseError: Connection 0 was disconnected when calling `startSession`
    at NativeConnection.startSession

我的代码:

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

学习了@nestjs/mongoose找到了解决办法。这里的猫鼬没有任何联系。这是返回错误的原因。

解决方法:

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

在服务class的构造函数中,我们需要添加服务可以使用的连接参数。

export class AuthService {
constructor(
  // other dependencies...
  @InjectConnection() private readonly connection: mongoose.Connection){}

而不是

const transactionSession = await mongoose.startSession();
transactionSession.startTransaction();

我们现在将使用:

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

这样就可以解决startSession()后断线的问题