使用Node.js连接MongoDB遇getaddrinfo ENOTFOUND错误求助
Hey there! Let's break down what's going on here and get your Node.js-MongoDB connection working smoothly.
The Root Cause
That error message gives away the issue immediately: your Node.js code is trying to treat admin as a MongoDB server/host address, and it can't resolve that name. Worse, the duplicate admin in your connection string is confusing MongoDB—it’s interpreting the string as "connect to a host named admin on port admin:27017" (which doesn’t exist, hence the ENOTFOUND error).
Bitnami MEAN Stack MongoDB Defaults
First, let’s recap the standard setup for MongoDB in Bitnami’s AWS EC2 MEAN stack:
- MongoDB runs locally on your EC2 instance, listening on
127.0.0.1(localhost) port27017 - Authentication is enabled by default for security
- The default admin username is
root - You can find your MongoDB password by running this command on your EC2 instance:
Look for the line labeledcat /home/bitnami/bitnami_credentialsMongoDB Password.
Correct Connection String Format
You need to fix your connection string in database.js to follow MongoDB’s proper URI structure. Here are the two common use cases:
1. Connecting with Authentication (Recommended)
Since Bitnami enables auth by default, use this format (replace the placeholders with your actual details):
const mongoose = require('mongoose'); // If using Mongoose mongoose.connect('mongodb://root:YOUR_BITNAMI_MONGO_PASSWORD@127.0.0.1:27017/YOUR_DATABASE_NAME?authSource=admin') .then(() => console.log('MongoDB connected successfully!')) .catch(err => console.error('MongoDB connection failed:', err));
- The
authSource=adminparameter tells MongoDB to use theadmindatabase to verify your credentials—this is required for Bitnami’s setup.
2. If You Disabled Authentication (Not Recommended)
If you turned off auth (not advised for production), your string is simpler:
mongoose.connect('mongodb://127.0.0.1:27017/YOUR_DATABASE_NAME')
Quick Validation Checks
- Confirm MongoDB is listening on localhost: Run
netstat -plnt | grep mongodon your EC2 instance. You should see output liketcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 1234/mongod - Ensure you’re not using a remote host address: Since your Node.js app runs on the same EC2 instance as MongoDB,
127.0.0.1is the correct host to connect to.
Once you update your connection string with the right values, restart your Node.js server and the connection should work as expected!
内容的提问来源于stack exchange,提问作者Arun-

