Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MongoDB's native NodeJS Driver, when to use MongoClient constructor and when to use the Db constructor?

The MongoClient and Db constructors are described in the manual. When should you use one and when should you use the other?

like image 914
Leila Hamon Avatar asked Jul 25 '13 23:07

Leila Hamon


Video Answer


1 Answers

MongoClient should normally be preferred, the only major issue is that it is newer (1.2+).

Let us quote the manual:

MongoClient or how to connect in a new and better way

From driver version 1.2 we introduce a new connection Class that has the same name across all our official drivers. This is to ensure that we present a recognizable front for all our API’s. This does not mean that your existing application will break, but rather that we encourage you to use the new connection api to simplify your application development.

Furthermore, we are making the new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing connection class Db that has acknowledgements turned off.

The two biggest changes are thus the fact MongoClient acknowledges all writes to DB and when the actual database is chosen in the connection.

With MongoClient:

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"); // The DB is set here

  mongoClient.close();
});

vs with Db:

// db is selected in the next line, unlike with MongoClient and most drivers to other databases
var db = new Db('test', new Server('locahost', 27017)); 
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  db.on('close', test.done.bind(test));
  db.close();
});
like image 69
Benjamin Gruenbaum Avatar answered Oct 15 '22 05:10

Benjamin Gruenbaum