pannshenn
pannshenn

Reputation: 3

What is the difference between these two ways of connecting to MongoDB in Node.js

I came across two different ways of connecting to MongoDB thru Node.js. What is the difference? Pros and cons?

  1. Use .connect() method
let express = require('express')
let mongodb = require('mongodb')

let app = express()
let db
let connectionString = ''
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(port)
})
  1. Use .MongoClient.connect() as shown in MongoDB driver's official Quick Start document
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
 
// Connection URL
const url = 'mongodb://localhost:27017';
 
// Database Name
const dbName = 'myproject';
 
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
 
  const db = client.db(dbName);
 
  client.close();
});

Upvotes: 0

Views: 266

Answers (1)

Tom Mettam
Tom Mettam

Reputation: 2973

The MongoClient class was introduced as an attempt to modernise and unify the interface across all platforms.

It doesn't really offer any benefit over the "old" way (except that it has write acknowledgements turned on by default), but you are encouraged to use MongoClient for new applications. It seems likely that the old method may be deprecated in the future.

https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

Upvotes: 1

Related Questions