程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Typescript 中的 Mongoose.startSession 是什么类型?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Typescript 中的 Mongoose.startSession 是什么类型??

开发过程中遇到Typescript 中的 Mongoose.startSession 是什么类型?的问题如何解决?下面主要结合日常开发的经验,给出你关于Typescript 中的 Mongoose.startSession 是什么类型?的解决方法建议,希望对你解决Typescript 中的 Mongoose.startSession 是什么类型?有所启发或帮助;

我有一个使用 mongoose 的 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,{}>) => voID'.

我应该使用哪种类型的会话?

解决方法

我发现要在 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

大佬总结

以上是大佬教程为你收集整理的Typescript 中的 Mongoose.startSession 是什么类型?全部内容,希望文章能够帮你解决Typescript 中的 Mongoose.startSession 是什么类型?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: