Skip to content
Discussion options

You must be logged in to vote

这个不是 @midwayjs/typegoose 对事务做了限制,主要是 TypeScript await using 对类型的要求和 Mongoose/MongoDB driver 当前公开出来的类型不匹配。@midwayjs/typegoose 注入的是 Typegoose/Mongoose 原生 Model,this.db.startSession() 返回的是 mongoose.ClientSession,而 TS 的 await using 需要这个对象在类型上有 [Symbol.asyncDispose]()。现在这层类型没有稳定暴露出来,所以会出现你看到的类型错误。

建议先按 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 Use…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by pecasha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
type: question / discussion This issue or pull request need be discussion
2 participants