英文:
Can't connect MongoDB to Node.js
问题
我是一个完全的Web应用程序开发新手,今天我按照这个YouTube视频教程连接MongoDB到Node.js:https://www.youtube.com/watch?v=bhiEJW5poHU。
我按照YouTube视频中的一切操作,下面是我从教程中精确复制的代码:
server.js
/* 连接到MongoDB数据库 */
const express = require('express');
const app = express();
const mongoose = require('mongoose')
const MongoDBpassword = process.env.MONGODB_PASSWORD
const uri = `mongodb+srv://giangpham:${MongoDBpassword}@cluster0.q22wdfo.mongodb.net/?retryWrites=true&w=majority`;
async function connect() {
try {
await mongoose.connect(uri)
console.log("已连接到MongoDB")
} catch(error) {
console.log("连接到MongoDB时发生错误:", error)
}
}
connect()
然而,我无法连接,以下是我收到的错误消息:连接到MongoDB时发生错误:MongooseServerSelectionError:无法连接到MongoDB Atlas集群中的任何服务器。一个常见的原因是您尝试从未在白名单上的IP访问数据库。确保您的当前IP地址在Atlas集群的IP白名单上:https://www.mongodb.com/docs/atlas/security-whitelist/
我尝试使用MongoDB网站上的示例代码:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://giangpham:<password>@cluster0.q22wdfo.mongodb.net/?retryWrites=true&w=majority";
// 使用MongoClientOptions对象创建一个MongoClient以设置稳定API版本
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function run() {
try {
// 将客户端连接到服务器(v4.7中可选)
await client.connect();
// 发送ping以确认成功连接
await client.db("admin").command({ ping: 1 });
console.log("发送ping到您的部署。您已成功连接到MongoDB!");
} finally {
// 确保客户端在完成/出错时关闭
await client.close();
}
}
run().catch(console.dir);
以下是我收到的错误消息:
MongoServerSelectionError: read ECONNRESET at Timeout._onTimeout (/Users/giangpham/Desktop/writer-cave/writer_cave/server/node_modules/mongodb/lib/sdam/topology.js:278:38) at listOnTimeout (node:internal/timers:568:17) at process.processTimers (node:internal/timers:511:7) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'ac-w1pnlco-shard-00-01.q22wdfo.mongodb.net:27017' => [ServerDescription], 'ac-w1pnlco-shard-00-02.q22wdfo.mongodb.net:27017' => [ServerDescription], 'ac-w1pnlco-shard-00-00.q22wdfo.mongodb.net:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: 'atlas-13ubyp-shard-0', maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {}
英文:
I am a total newbie in Web App development, and today I followed this YouTube video tutorial to connect MongoDB to Node.js: https://www.youtube.com/watch?v=bhiEJW5poHU.
I followed everything in the Youtube video and here are my code, which I follow exactly from the tutorial:
server.js
/* Connect to MongoDB database */
const express = require('express');
const app = express();
const mongoose = require('mongoose')
const MongoDBpassword = process.env.MONGODB_PASSWORD
const uri = `mongodb+srv://giangpham:${MongoDBpassword}@cluster0.q22wdfo.mongodb.net/?retryWrites=true&w=majority`;
async function connect() {
try {
await mongoose.connect(uri)
console.log("Connected to MongoDB")
} catch(error) {
console.log("Error connecting to MongoDB: ", error)
}
}
connect()
However, I can't connect it and this is the error I got: Error connecting to MongoDB: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/
I tried using the sample code from the MongoDB website:
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://giangpham:<password>@cluster0.q22wdfo.mongodb.net/?retryWrites=true&w=majority";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
and this is the error I got:
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (/Users/giangpham/Desktop/writer-cave/writer_cave/server/node_modules/mongodb/lib/sdam/topology.js:278:38)
at listOnTimeout (node:internal/timers:568:17)
at process.processTimers (node:internal/timers:511:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-w1pnlco-shard-00-01.q22wdfo.mongodb.net:27017' => [ServerDescription],
'ac-w1pnlco-shard-00-02.q22wdfo.mongodb.net:27017' => [ServerDescription],
'ac-w1pnlco-shard-00-00.q22wdfo.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-13ubyp-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
答案1
得分: 0
你的第一个错误,出现这个错误的最常见原因是你尝试连接的IP地址未在你的MongoDB Atlas集群的IP白名单中。第二个错误有一些原因,最好的方法是将你的IP添加到白名单中。
设置步骤 - 访问MongoDB Atlas仪表板并登录。导航到"网络访问"部分,现在添加这个IP,以便你可以从任何IP访问。
英文:
Your first error, The most common reason for this error is that the IP address you're trying to connect from is not on the IP whitelist for your MongoDB Atlas cluster.
There are a few reasons for the second one, It will be best if you can whitelist your IP.
Set up - Visit the MongoDB Atlas dashboard and log in. Navigate to the "Network Access" section, and now add this IP, by which you can access from any IP.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论