skip to Main Content

This is resolved. Please look at the answers

I am following this lab:
https://github.com/AzureCosmosDB/Azure-OpenAI-Node.js-Developer-Guide/tree/main/Labs/first_cosmos_db_application

After I received errors, I just copied the lab code so there should not be code side errors.

In my .env file, I have:

MONGODB_URI=mongodb+srv://<user>:<password>@phase-1-db.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000

where I replaced the user whit my Admin username in the Azure Cosmos DB for MongoDB (vCore) Overview section

I replaced the password wit hthe password I set with Admin Username.

The code in index.js I use to connect is

require('dotenv').config();
const { MongoClient } = require('mongodb');

async function main() { 
    // initialize the MongoDB client
    const client = new MongoClient(process.env.MONGODB_URI);
    
    // connects to the database service and outputs messages to the console to indicate the connection status.
    try {
        await client.connect();
        console.log('Connected to MongoDB');
      } catch (err) {
        console.error(err);
      } finally {
        await client.close();
        console.log('Disconnected from MongoDB');
      }
}

main().catch(console.error);

I have copied the package.json and runed npm install

{  
  "name": "mongodb-nodejs-devguide-first-cosmos-db-application",  
  "version": "1.0.0",  
  "description": "A Node.js application that connects to MongoDB",  
  "main": "index.js",  
  "scripts": {  
    "start": "node index.js"  
  },  
  "dependencies": {  
    "mongodb": "6.3.0",
    "dotenv": "16.4.4"
  },  
  "author": "Microsoft",  
  "license": "MIT"  
}  

Then I run npm start, and I received this error:

npm start

> [email protected] start
> node index.js

MongoServerSelectionError: Server selection timed out after 30000 ms
    at EventTarget.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/sdam/topology.js:276:34)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:822:20)
    at EventTarget.dispatchEvent (node:internal/event_target:757:26)
    at abortSignal (node:internal/abort_controller:374:10)
    at TimeoutController.abort (node:internal/abort_controller:396:5)
    at Timeout.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/utils.js:1011:92)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'c.phase-1-db.mongocluster.cosmos.azure.com:10260' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}
Disconnected from MongoDB

see descriptions   

2

Answers


  1. Chosen as BEST ANSWER

    Oh Thank you very much Balaji, David Makogon and every body who helped. I deeply appreciate your kindness and time putted in to assist me. This problem is solved with my original code by navigating:

    1. Overview
    2. Connectivity method:Public access
    3. click on "Public access"
    4. Scroll to public access and check "Allow public access from Azure service and resources with Azure to this cluster"
    5. click "+ Add current client IP address"
    6. Save and retry

    enter image description here


  2. MongoServerSelectionError: Server selection timed out after 30000 ms

    The above error is occurred due to mismatch of connection string, hostname or port. Try with the below code to create a Database and a Container in Azure Cosmos Mongo DB API. The sample data is inserted into the database successfully as shown in the output below:

    const { MongoClient } = require('mongodb');
    
    const uri = "*****";
    
    const client = new MongoClient(uri);
    
    async function run() {
      try {
        await client.connect();
    
        const database = client.db('newdb');
    
        const collection = database.collection('newcoll');
    
        await client.db("newdb").createCollection("newcoll");
    
        const documents = [
          { key: 'Id' },
          { key: 'Name' },
          { key: 'Age' }
        ];
        const result = await collection.insertMany(documents);
        console.log(`Inserted ${result.insertedCount} documents`);
    
        const query = { key: { $in: ['Id', 'Name', 'Age'] } };
        const cursor = collection.find(query);
    
        await cursor.forEach(console.log);
      } finally {
        await client.close();
      }
    }
    
    run().catch(console.error);
    

    Output:
    enter image description here

    enter image description here

    • Refer this document for more information on Azure Cosmos Mongo DB.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search