mongoose - 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();
}
解决方案
我在研究@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()后断线的问题。
推荐阅读
- visual-studio-2010 - 模板 MVC 3 在 Visual Studio 2010 中不起作用
- c# - 如何在 Visual Studio 中配置方法的摘要注释
- javascript - 使用 JavaScript 和 ViewModel 在 Asp.NET MVC 5 应用程序中发布数据
- android - 在xamarin表单android中未附加到窗口管理器崩溃的视图
- asp.net-mvc - 如何在 razor-engine 中的 ModelMetadata 对象上设置 DisplayFormatString 属性?
- angularjs - AngularJS 可以将用户路由到内存中同一视图的同一实例吗?
- java - 如何在不重新加载窗口的情况下单击按钮时在 JSP 中进行更新查询?
- mysql - 对多个内部联接进行分组
- jmeter - 无法在 Windows 10 64 位中使用 jdk 版本 1.8.0.45 访问 Jarfile ApacheJMeter.jar Errorlevel=1
- java - 时间和/或日期的排序