{已解决} {感谢那些帮助我的人!} MongoServerSelectionError: 服务器选择在 30000 毫秒后超时

问题描述 投票:0回答:2

这个问题已经解决了。请看一下答案

我正在关注这个实验室: https://github.com/AzureCosmosDB/Azure-OpenAI-Node.js-Developer-Guide/tree/main/Labs/first_cosmos_db_application

收到错误后,我只是复制了实验室代码,因此不应出现代码端错误。

在我的 .env 文件中,我有:

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

我在 Azure Cosmos DB for MongoDB (vCore) 概述部分中用我的管理员用户名替换了用户

我用管理员用户名设置的密码替换了密码。

我用来连接的index.js中的代码是

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

我已复制 package.json 并运行 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"  
}  

然后我运行 npm start,收到此错误:

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   
node.js mongodb azure azure-cosmosdb azure-cosmosdb-mongovcore
2个回答
0
投票

MongoServerSelectionError:服务器选择在 30000 毫秒后超时

上述错误是由于连接字符串、主机名或端口不匹配而发生的。尝试使用以下代码在 Azure Cosmos Mongo DB API 中创建

Database
Container
。示例数据已成功插入数据库,如下输出所示:

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

输出: enter image description here

enter image description here

  • 请参阅此文档,了解有关 Azure Cosmos Mongo DB 的更多信息。

0
投票

这里完整列出我在新代码中遇到的问题:

(我高度怀疑是因为我没有使用正确的用户名和密码。在哪里可以找到此连接所需的正确用户名和密码?)这是在概述 -> 管理员用户名中吗?

但我不知道我错在哪里,有了这个新答案,我仍然遇到同样的错误。我是这样做的:

  1. 我将代码复制到我的index.js中

  2. 我替换了 const uri = "*****"; 中的 *****和 mongodb+srv://:@phase-1-db.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000

但是,我仍然收到以下错误:

Users-MBP:NodeJS user1$ 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:289: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:976: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) {}
}

然后我查看了答案中提供的文档,并将 URI 更改为 :mongodb://:@phase-1-db.documents.azure.com:10255/?ssl=true

但是,我仍然收到错误:

Node.js v21.7.3
Users-MBP:NodeJS user1$ npm start

> [email protected] start
> node index.js

MongoServerSelectionError: getaddrinfo ENOTFOUND phase-1-db.documents.azure.com
    at EventTarget.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/sdam/topology.js:289: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:976:92)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'phase-1-db.documents.azure.com:10255' => [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) {},
  [cause]: MongoNetworkError: getaddrinfo ENOTFOUND phase-1-db.documents.azure.com
      at connectionFailureError (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/cmap/connect.js:353:20)
      at TLSSocket.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/cmap/connect.js:268:44)
      at Object.onceWrapper (node:events:634:26)
      at TLSSocket.emit (node:events:519:28)
      at emitErrorNT (node:internal/streams/destroy:169:8)
      at emitErrorCloseNT (node:internal/streams/destroy:128:3)
      at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
    [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
    [cause]: Error: getaddrinfo ENOTFOUND phase-1-db.documents.azure.com
        at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26) {
      errno: -3008,
      code: 'ENOTFOUND',
      syscall: 'getaddrinfo',
      hostname: 'phase-1-db.documents.azure.com'
    }
  }
}
Users-MBP:NodeJS user1$ 

我以为是.documents.azure.com的错误,所以我把完整的uri改为:mongodb://:@phase-1-db.mongocluster.cosmos.azure.com:10255/?ssl=true

但我仍然有同样的错误:

Users-MBP:NodeJS user1$ npm start

> [email protected] start
> node index.js

MongoServerSelectionError: getaddrinfo ENOTFOUND phase-1-db.mongocluster.cosmos.azure.com
    at EventTarget.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/sdam/topology.js:289: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:976:92)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'phase-1-db.mongocluster.cosmos.azure.com:10255' => [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) {},
  [cause]: MongoNetworkError: getaddrinfo ENOTFOUND phase-1-db.mongocluster.cosmos.azure.com
      at connectionFailureError (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/cmap/connect.js:353:20)
      at TLSSocket.<anonymous> (/Users/user1/Desktop/github/Azure-OpenAI-Tutorials/first_cosmos_db_application/NodeJS/node_modules/mongodb/lib/cmap/connect.js:268:44)
      at Object.onceWrapper (node:events:634:26)
      at TLSSocket.emit (node:events:519:28)
      at emitErrorNT (node:internal/streams/destroy:169:8)
      at emitErrorCloseNT (node:internal/streams/destroy:128:3)
      at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
    [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
    [cause]: Error: getaddrinfo ENOTFOUND phase-1-db.mongocluster.cosmos.azure.com
        at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:118:26) {
      errno: -3008,
      code: 'ENOTFOUND',
      syscall: 'getaddrinfo',
      hostname: 'phase-1-db.mongocluster.cosmos.azure.com'
    }
  }
}
Users-MBP:NodeJS user1$ 
© www.soinside.com 2019 - 2024. All rights reserved.