node.jsazureazure-cosmosdbazure-cosmosdb-mongoapi

Why is Node.JS Mongo.Connect() (Azure Cosmos DB) Not Responding/Returning Any Error?


I am doing a training exercise that is supposed to connect to a Azure Cosmos DB for MongoDB database using Node.JS however it doesn't seem that the connection is being established and while I'm new to Node.JS/Cosmos DB/Mongo, it doesn't appear that any error/exception is being thrown.

Here is a snippet of the code that opens the connection (I added line breaks to connstring for readibility):

var connstring = "mongodb://jobinfoaccount:xxxxxx
                  @xxxxx.mongo.cosmos.azure.com:10255/ssl=true
                  &replicaSet=globaldb&retrywrites=false
                  &maxIdleTimeMS=120000
                  &appName=@xxxxx@"

MongoClient.connect(connstring, function(err, client) {
if (err) {console.log(err)}

    console.log("connected to Cosmos DB Mongo API");
    db = client.db("xxxxx"); 

    //listen to port 3001
    app.listen(3001, () => {
    console.log('listening on 3001')
});

When I debug the server.js file in VSCode, there is no error thrown and the code execution passes completely over lines 195 through 205 and ends on line 206, doesn't hit any breakpoints that I've set and I'm not sure why this is happening:

enter image description here

Again, I'm new to to the aforementioned technologies, but I would have expected at least an exception however I am not seeing one in VSCode Terminal or Output Window, which makes me wonder if there's something wrong with my connection string although I double checked with the book as well as examples online and it appears to be okay.

I should also point out that per the book I am following for this example, I am getting my connection string from Azure Portal here:

enter image description here


Solution

  • Connect to a Azure Cosmos DB for MongoDB database using Node.JS:

    Below are the steps followed to connect Azure Cosmos DB for MongoDB using NodeJs:

    Code I tried with:

    const { MongoClient } = require('mongodb');
    async  function  main() {
     const  uri = "****";
     const  client = new  MongoClient(uri);
     try {
        await  client.connect();
        console.log("Connected to the database");
        const  database = client.db("newDb");
        const  collection = database.collection("newColl");
    
        // Query and print data
        const  query = { age: { $gte:  28 } };
        const  documents = await  collection.find(query).toArray();
        console.log("Documents retrieved:");
        documents.forEach(doc => {
        console.log(doc);
        });
     } catch (error) {
     console.error("Error:", error);
     } finally {
     await  client.close();
     console.log("Connection closed");
      }
    }
    main().catch(console.error);
    

    Output: