英文:
Can't connect MongoDB to Node.js
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我是一个完全的Web应用程序开发新手,今天我按照这个YouTube视频教程连接MongoDB到Node.js:https://www.youtube.com/watch?v=bhiEJW5poHU。
我按照视频中的所有步骤进行操作,以下是我从教程中完全复制的代码:
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("Connected to MongoDB")
} catch(error) {
console.log("Error connecting to MongoDB: ", error)
}
}
connect()
然而,我无法连接,这是我收到的错误信息: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/
我尝试使用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("Pinged your deployment. You successfully connected to 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 控制台并登录。
- 导航到 "Network Access" 部分,然后添加你可以从任何 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论