[Support] typegoose 的 startSession 不支持用 using 声明吗? #4352
-
Describe the problem(描述问题)我使用 例如以下代码: import { Provide } from "@midwayjs/decorator";
import { InjectEntityModel } from "@midwayjs/typegoose";
import { ReturnModelType } from "@typegoose/typegoose";
import { UserEntity } from "@/entity/user.entity";
@Provide()
export class UserServer {
@InjectEntityModel(UserEntity)
private db: ReturnModelType<typeof UserEntity>;
public async create() {
await using session = this.db.startSession();
await session.withTransaction(async () => {
// 事物操作
});
}
}Midway Versions(Midway 版本)✓ @midwayjs/faas-typings(not installed) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
这个不是 建议先按 Mongoose 官方更通用的写法处理: public async create() {
const session = await this.db.startSession();
try {
await session.withTransaction(async () => {
// 事务操作,记得把 session 传给对应的写操作
// await this.db.create([{ ... }], { session });
});
} finally {
await session.endSession();
}
}如果只是想少写一点,可以封装一个本地 helper: async function withMongoSession<T>(
model: ReturnModelType<typeof UserEntity>,
fn: (session: mongoose.ClientSession) => Promise<T>
) {
const session = await model.startSession();
try {
return await session.withTransaction(() => fn(session));
} finally {
await session.endSession();
}
}不太建议在业务里直接通过类型断言强行让 |
Beta Was this translation helpful? Give feedback.
这个不是
@midwayjs/typegoose对事务做了限制,主要是 TypeScriptawait using对类型的要求和 Mongoose/MongoDB driver 当前公开出来的类型不匹配。@midwayjs/typegoose注入的是 Typegoose/Mongoose 原生 Model,this.db.startSession()返回的是mongoose.ClientSession,而 TS 的await using需要这个对象在类型上有[Symbol.asyncDispose]()。现在这层类型没有稳定暴露出来,所以会出现你看到的类型错误。建议先按 Mongoose 官方更通用的写法处理:
如果只是想少写一点,可以封装一个本地 helper: