Answer the question
In order to leave comments, you need to log in
How to close and open a connection in mongodb?
app.get('/games',function(req, res){
mongoClient.connect(function(err, client){
var response = '<table>\n';
const db = client.db("eshopdb");
const collection = db.collection("games");
if(err){
console.error(err);
}
else {
console.log("mongoClient.connect is OK");
};
collection.find().sort({title_eu: 1}).toArray(function(err, result) {
if (err) throw err;
var n = 0;
each(result,function(docs){
n++;
response = response + '<tr><td>' + docs.title_eu + '</td><td><a href="/game/' + docs._id + '">' + docs._id + '</td></tr>\n';
closeclient(n);
});
respnse = response + '</table>\n';
res.send(response);
function closeclient(n){
if (n == result.length){
client.close();
console.log(n, result.length)
var n = 0;
console.log("mongoClient.connect is close");
}
}
});
});
});
Answer the question
In order to leave comments, you need to log in
Closing and opening a connet is a very time-consuming operation. There is such a thing as a connection pool, by default it's like 100, so open the Connect and hold it so that the pool works. If there are few requests, you can reduce the pool, say, to 50.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question