Answer the question
In order to leave comments, you need to log in
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);
}
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}
));
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
}
MongoExpiredSessionError: Cannot use a session that has ended
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question