gpt4 book ai didi

mongoose - Nestjs:如何使用 Mongoose 启动事务 session ?

转载 作者:行者123 更新时间:2023-12-05 00:53:26 26 4
gpt4 key购买 nike

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

最佳答案

我在研究@nestjs/mongoose 后找到了解决方案。这里的 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()后断线的问题了。

关于mongoose - Nestjs:如何使用 Mongoose 启动事务 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67879357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com