首页 > 解决方案 > Nestjs:如何使用猫鼬启动事务会话?

问题描述

使用事务的 mongoose 文档很简单,但是当在 nestjs 中遵循它时,它会返回错误:

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

标签: mongoosenestjs

解决方案


我在研究@nestjs/mongoose 后找到了解决方案。这里的猫鼬与它无关。这是返回错误的原因。

解决方案:

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

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

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()后断线的问题。


推荐阅读