'Abstracting MongoDb Connection try, catch, finally with a callback

I tried to abstract the try, catch, finally structure in a withConnection() function, so the code for e.g. upsert() is neatly. But it gives an error "MongoExpiredSessionError: Cannot use a session that has ended"

What do I do wrong?

import 'dotenv/config';
import { MongoClient, ObjectId } from "mongodb";

export class Base {
    constructor(db, collection) {
        this.client = new MongoClient(process.env.connection);
        this.db = db;
        this.collection = collection;
        this.con = this.client.db(db).collection(collection);
    }

    async withConnection(callback) {
        await this.client.connect();
        try {
            return callback();
        } catch (err) {
            console.log(err);
        } finally {
            await this.client.close();
        }
    }

    async upsert(query, payload) {
        await this.withConnection(() => {
            return this.con.updateOne(query, payload, { upsert: true })
        })
    }

    // ...
}


Solution 1:[1]

This works!

import 'dotenv/config';
import { MongoClient, ObjectId } from "mongodb";

export class Base {
    constructor(db, collection) {
        this.client = new MongoClient(process.env.connection);
        this.db = db;
        this.collection = collection;
        this.con = this.client.db(this.db).collection(this.collection);
    }

    async withConnection(callback = null) {
        await this.client.connect();
        try {
            return await callback();
        } catch (err) {
            console.log(err);
        } finally {
            if (callback !== null) {
                await this.client.close();
            }
        }
    }

    async upsert(query, payload) {
        await this.withConnection(async () => {
            return await this.con.updateOne(query, payload, { upsert: true })
        })
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nonnial