I have this below code it works correctly but should I close the connection after returning the data? If yes so how to close the connection?
// project.db.js
const { MongoClient, ObjectId } = require("mongodb");
const { mongo_uri, dbName } = require("../config/constants");
// connect method
function connection() {
return MongoClient.connect(mongo_uri);
}
// async function which read data
exports.allProject_tasks = async (space_id) => {
try {
const result = await connection();
const db = await result.db(dbName);
const payload = await db
.collection("tasks")
.find({
user_space_id: ObjectId(space_id),
})
.toArray();
return payload;
} catch {
return 400;
}
};
CodePudding user response:
It is always best to close the connection when the job is done from app side to release the allocated connection resources on database server side( mongoDB allocated ~1MB per connection meaning that if you open 1000 connections your server will allocate ~1GB only for connections) , and if you leave the resource to be released by the connection timeouts this could lead to issues when server is under high load if the timeout is higher.
