Simple way to Connect mongoDB with core Node.JS

suggest change

The mongodb package is the driver. It is not a module named inside Node's core. Driver 4 connects with a promise. The database name is passed to client.db().

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

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

client.connect().then(function () {
  const db = client.db('MyDb');
  console.log('successfully connected to mongoDB.');
  return db.command({ ping: 1 });
}).then(function () {
  return client.close();
}).catch(function (err) {
  console.log('connection failed.');
  console.error(err);
});

Feedback about page:

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



Table Of Contents