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