I am creating a basic application to connect my Nodejs code to MongoDB but the code is not getting executed. Have attached image for the output I am getting. It is not printing to console
got db connection
Have checked that the MongoDB is up and running and I am able to execute normal MongoDB operations using Mongo Client and Compass using mongodb://127.0.0.1:27017. Is there any missing configuration or any changes that need to be done on the code side.
- MongoDB version 5.0
- NodeJS version 18.13.0
- npm version 8.19.3
var MongoC = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017";
console.log('waiting db connection')
MongoC.connect(url, function (err, db) {
//control not reaching here-- Expected to log to console 'got db connection'
console.log('got db connection');
if (err) {
throw err;
}
console.log('hello');
});
3
Answers
Try adding the
await
keyword at the start of line #4.MongoClient.connect
is an async function.Example from documentation:
https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connect/#std-label-node-connect-to-mongodb
Mongodb standard uri is:
mongodb://MONGODB_USERNAME:MONGODB_PASSWORD@MONGODB_HOST:MONGODB_PORT
Did you save the file before running it? :))))
Use this:
Try changing mongodb version in package.json to ^4.x.x and then npm install to install the required packages and their dependencies.