简体   繁体   中英

Better approach using MongoDB native driver in NodeJS

Here is the code snippet on which my question is

var MongoClient = require('mongodb').MongoClient
  , Server = require('mongodb').Server;

var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
  var db1 = mongoClient.db("mydb");
  mongoClient.close();
});

Ill be using the same mongoClient object in my entire application to make all db operations , but isnt it a consuming process to open and connect to the database for every request ???? Im referring to the following lines of code when i make use of the mongoClient object

mongoClient.open(function(err, mongoClient) {
      var db1 = mongoClient.db("mydb");
      mongoClient.close();
});

Or is it better to keep the connection opened with the connection to the right database and use the same object for all read/writes into DB ???If this is the better approach then how can i make use of the db1 object in my other modules to directly do the read/writes into the mongo without have to open it everytime ??

MongoClient is a connection pool, generally meant to be opened when you start the application and not closed until you shut it down. So you absolutely don't want to be opening and closing it on each request; just leave it open and share it throughout your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM