收到错误后,我只是复制了实验室代码,因此不应出现代码端错误。
在我的 .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
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);
输出: