Simple way to Connect mongoDB with core Node.JS
suggest changeThe 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);
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents