skip to Main Content

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');
});

Output:
Output it only displays 'Waiting db connection'

3

Answers


  1. Try adding the await keyword at the start of line #4. MongoClient.connect is an async function.

    Example from documentation:

    const { MongoClient } = require("mongodb");
    // Connection URI
    const uri =
      "mongodb+srv://sample-hostname:27017/?maxPoolSize=20&w=majority";
    // Create a new MongoClient
    const client = new MongoClient(uri);
    async function run() {
      try {
        // Connect the client to the server (optional starting in v4.7)
        await client.connect();
        // Establish and verify connection
        await client.db("admin").command({ ping: 1 });
        console.log("Connected successfully to server");
      } finally {
        // Ensures that the client will close when you finish/error
        await client.close();
      }
    }
    run().catch(console.dir);
    

    https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connect/#std-label-node-connect-to-mongodb

    Login or Signup to reply.
    1. Mongodb standard uri is:
      mongodb://MONGODB_USERNAME:MONGODB_PASSWORD@MONGODB_HOST:MONGODB_PORT

    2. Did you save the file before running it? :))))

    3. Use this:

    async function main(){
        /**
         * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
         * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
         */
        const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
     
    
        const client = new MongoClient(uri);
     
        try {
            // Connect to the MongoDB cluster
            await client.connect();
     
            // Make the appropriate DB calls
            await  listDatabases(client);
     
        } catch (e) {
            console.error(e);
        } finally {
            await client.close();
        }
    }
    
    main().catch(console.error);
    Login or Signup to reply.
  2. Try changing mongodb version in package.json to ^4.x.x and then npm install to install the required packages and their dependencies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search