【问题标题】:Nestjs: How to use mongoose to start a session for transaction?Nestjs:如何使用猫鼬启动事务会话?
【发布时间】:2021-08-24 23:52:09
【问题描述】:

使用事务的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();
    }

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

    我在研究@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()后断线的问题了。

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2019-12-22
      • 2018-11-24
      • 1970-01-01
      • 2018-08-29
      • 2020-10-15
      • 2019-08-04
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多