V
V
Vladimir2022-03-28 18:12:43
JavaScript
Vladimir, 2022-03-28 18:12:43

How to close mongodb connection when using same client in multiple endpoints?

Hello. Wrote a fairly simple back-end on a rest-api with mongo, each request I have comes from a pipe after data validation, here is an example:

get_events_pipe.js

export default function eventsPipe(req, res, eventSchema, validator, db) {
    db.query('events')
        .then(async collection => {

            const {client, find} = db;

            const id = +req.body.id;

            const events = validator({id}, eventSchema.getEvents);

            if(events) {
                await find(collection, {userID: id}).then(data => {
                    if(data.length) {
                        return data
                    }
                    throw 'Events not found';
                }).then(events => {
                    res.send({events});
                    return events
                }).then(() => client.close()).catch(() => { // После завершения я вызываю закрытие соединения
                    res.send({events:[]});
                }).finally(console.log);
            } else {
                console.error('Empty property in object user');
            }

        })
        .catch(console.error);
}


get_events_endpoint
import mongo_db from './mongo_db/config.js';
const {query, client} = mongo_db;

app.post('/getEvents', (req, res) => eventsPipe(
    req,
    res,
    eventSchema,
    validator,
    {query, client, find}
));


My mongo config looks like this:

db_config.js
import {MongoClient} from "mongodb";

const url = 'myMongoURL';
const client = new MongoClient(url);
const dbName = 'map';

export default {
    query: async function (collectionName) {
        await client.connect();
        const db = client.db(dbName);
        return db.collection(collectionName);
    },
    client: client
}


I get this error randomly, let's say 3 requests pass - 1 doesn't:
MongoExpiredSessionError: Cannot use a session that has ended


The first query on Google: https://stackoverflow.com/questions/59816298/how-t...
Here they offer a counter or asynchrony, the counter looks like a crutch, and I already use asynchrony.

Please tell me what can I do in this situation?

Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question