【问题标题】:What type is Mongoose.startSession in Typescript?Typescript 中的 Mongoose.startSession 是什么类型?
【发布时间】:2021-07-06 17:20:51
【问题描述】:

我有一个使用猫鼬的 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.js typescript express mongoose transactions


【解决方案1】:

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

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

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

MongoError: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 2018-10-13
    • 2017-06-07
    • 2017-10-20
    • 2021-04-12
    • 2019-03-11
    • 2021-02-25
    • 2015-09-30
    • 2017-11-20
    相关资源
    最近更新 更多