Reputation: 3
I came across two different ways of connecting to MongoDB thru Node.js. What is the difference? Pros and cons?
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)
})
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
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