I
I
Ivan2019-03-07 09:12:54
MongoDB
Ivan, 2019-03-07 09:12:54

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");
                }
            }
        });   
    });
});

The first query retrieves all documents from the database. Through the closeclient(n) function, I know that all documents are displayed and close the connection to mongodb. If you refresh the page, then an error occurs, because. The connection is closed, but a new one does not open. If you remove closeclient(n) then there is no error. But it seems to me that you need to close the connections to the database after use, and not save them. How to implement it correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Max Abzalov, 2019-03-14
@Gvald

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 question

Ask a Question

731 491 924 answers to any question