I have an Express/Typescript project using mongoose, made a loader like this:
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:
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?