0

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'

  • It might be helpful to add a link to the example within the official documentation that you are referencing, to ensure you are trying to implement the exact same thing. – user1063287 Feb 06 '23 at 17:24
  • http://mongodb.github.io/node-mongodb-native/2.2/api/index.html a similar example – user2821056 Feb 06 '23 at 20:02

3 Answers3

0

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

Richard
  • 2,226
  • 2
  • 19
  • 35
  • This did not work. Thanks for taking a look. – user2821056 Feb 06 '23 at 17:14
  • Can you run the documentation example if you replace the url with your own? – Richard Feb 06 '23 at 17:22
  • The first example on http://mongodb.github.io/node-mongodb-native/2.2/api/index.html is similar to the one I posted the question for but it also does not seem to work. Although I am able to connect with DB using the example at https://www.mongodb.com/developer/code-examples/javascript/node-connect-mongodb-3-3-2/ . – user2821056 Feb 06 '23 at 18:53
0
  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);
  • It gives this error ReferenceError: listDatabases is not defined – user2821056 Feb 06 '23 at 18:22
  • https://www.mongodb.com/developer/code-examples/javascript/node-connect-mongodb-3-3-2/ added listDatabases from here – user2821056 Feb 06 '23 at 18:26
  • You dont need to use listDatabases this is just an example. Check only your connection and sure your database service (Mongodb) be available. you can test with mongo compass. – Amin Alizadeh Feb 07 '23 at 09:28
0

Try changing mongodb version in package.json to ^4.x.x and then npm install to install the required packages and their dependencies.

KalyaniC
  • 1
  • 1