首页 > 解决方案 > Typescript 中的 Mongoose.startSession 是什么类型?

问题描述

我有一个使用猫鼬的 Express/Typescript 项目,制作了一个像这样的加载器:

    import mongoose from 'mongoose';
    import { Db } from 'mongodb';
    import config from '../config';
    
    export default async (): Promise<Db> => {
      const connection = await mongoose.connect(config.databaseURL, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useUnifiedTopology: true
      });
    
      return connection.connection.db;
    };
    
    export async function withTransaction (func: any) {
      const session = await mongoose.startSession();
    
      session.startTransaction();
    
      try {
        await func(session);
        await session.commitTransaction();
      } catch (error) {
        await session.abortTransaction();
        throw error;
      } finally {
        session.endSession();
      }
    }

我想做一笔交易,我做了什么:

return await withTransaction(async (session: ClientSession) => {
    try {
        const newTransit = await Transit.create(userData, {session});
        //...some other inserts
    } catch (e) {
        throw e;
    }
}

Typescript 在会话类型上显示此错误:

TS2769: No overload matches this call.
The last overload gave the following error.
Argument of type '{ session: ClientSession; }' is not assignable to parameter of type '(err: NativeError, doc: ITransit & Document<any, {}>) => void'.
Object literal may only specify known properties, and 'session' does not exist in type '(err: NativeError, doc: ITransit & Document<any, {}>) => void'.

我应该为会话使用什么类型?

标签: node.jstypescriptexpressmongoosetransactions

解决方案


我发现要在 create 方法中使用选项,我们必须将第一个参数作为数组传递。所以它会是这样的:

const newTransit = await Transit.create([userData], {session});

然后我们应该在需要 MongoDB 副本集的连接字符串中添加 retryWrites=false。以下是更多信息:

MongoError:此 MongoDB 部署不支持可重试写入。请将 retryWrites=false 添加到您的连接字符串


推荐阅读