Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js mongodb closing the connection

I am trying to use node.js with mongodb and following the tutorial at http://howtonode.org/express-mongodb

The code for opening the connection is

ArticleProvider = function(host, port) {
 this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
 this.db.open(function(){});
};

However i cannot see any connections being closed. But when i see the logs on the mongo console, i can see that are connections which open and they close after some time.

Does the connection close automatically? Will it be a problem when a large no of clients try to access the server? Where should the connection be closed?

Thanks

Tuco

like image 857
Tuco Avatar asked Sep 11 '12 07:09

Tuco


People also ask

How do I close a connection in MongoDB?

javascript, node.js, database, mongodb The MongoClient#close() method API documentation says: Close the client, which will close all underlying cached resources, including, for example, sockets and background monitoring threads.

How does node JS connect to MongoDB?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

Do I need to close Pymongo connection?

There's no need to close a Connection instance, it will clean up after itself when Python garbage collects it. You should use MongoClient instead of Connection ; Connection is deprecated. To take advantage of connection pooling, you could create one MongoClient that lasts for the entire life of your process.


2 Answers

In that example application, only a single ArticleProvider object is created for the application to share when serving requests. That object's constructor opens a db connection that won't be closed until the application terminates (which is fine).

So what you should see is that you get a new mongo connection each time you start your app, but no additional connections made no matter how many clients access the server. And shortly after you terminate your app you should see its connection disappear on the mongo side.

like image 119
JohnnyHK Avatar answered Oct 02 '22 21:10

JohnnyHK


node-mongodb-native provides a close method for Db objects and you can close your connection when you are finished by calling it.

var that = this;
this.db.open(function(){
    // do db work here

    // close the connection
    that.db.close();
});

If you don't close your connection, event loop keeps the connection open and your process doesn't exit. If you are building a web server where your process will not be terminated, it's not necessary for you to close the connection.

A better reference for node-mongodb-native can be found on https://github.com/mongodb/node-mongodb-native.

like image 44
Burcu Dogan Avatar answered Oct 02 '22 22:10

Burcu Dogan