[英]What type is Mongoose.startSession in Typescript?
I have an Express/Typescript project using mongoose, made a loader like this:我有一个使用 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();
}
}
I want to make a transaction and here what is I did:我想做一笔交易,我做了什么:
return await withTransaction(async (session: ClientSession) => {
try {
const newTransit = await Transit.create(userData, {session});
//...some other inserts
} catch (e) {
throw e;
}
}
Typescript shows this error on session type: Typescript 在 session 类型上显示此错误:
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'.
What type should I use for the session? session 应该使用什么类型?
I figured out that to use options in create method, we have to pass the first argument as an array.我发现要在 create 方法中使用选项,我们必须将第一个参数作为数组传递。 So it would be like this:
所以它会是这样的:
const newTransit = await Transit.create([userData], {session});
Then we should add retryWrites=false in our connection string that needs a MongoDB replica set.然后我们应该在需要 MongoDB 副本集的连接字符串中添加 retryWrites=false。 Here is more information:
以下是更多信息:
MongoError: This MongoDB deployment does not support retryable writes. MongoError:此 MongoDB 部署不支持可重试写入。 Please add retryWrites=false to your connection string
请将 retryWrites=false 添加到您的连接字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.