Simple example to Connect mongoDB from Node.JS

suggest change

myNewDB is the database name. MongoDB creates it on the first write, not when connect succeeds. Driver 4's connect returns a promise and does not pass a database object into a callback. On failure there is no client to close.

const { MongoClient } = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017');

client.connect().then(function () {
  console.log('Connected to DB');
  return client.db('myNewDB').command({ ping: 1 });
}).then(function () {
  return client.close();
}).catch(function (err) {
  console.log('Unable to connect DB. Error: ' + err);
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents