Connection Error with MongoDB and Express - node.js

Trying to connect my express app with mongodb atlas, but I keep getting this MongodbNetworkError
Server.js file
const express = require("express")
const mongoose = require("mongoose")
const dotenv = require("dotenv")
dotenv.config()
const app = express()
mongoose
.connect(process.env.MONGODB_KEY, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("MongoDB connected"))
.catch(err => console.error(err))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
Command Line
[nodemon] starting `node server.js`
Server running on port 5000
{ Error: getaddrinfo ENOTFOUND coolcluster-shard-00-00-wqaqv.mongodb.net coolcluster-shard-00-00-
wqaqv.mongodb.net:27017
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

You need to whitelist the IP address of your nodejs server in MongoDB.
After login to the account, Follow the steps
Go to IP Whitelist view.
a)In the Security section of the left navigation, click Network Access. The IP Whitelist tab displays.
b)Click plus icon Add IP Address.
https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries

Related

PostgreSQL error: `Error: connect ECONNREFUSED 127.0.0.1:5432`

I'm trying to make a request to postgreSQL from a Node and Express server on localhost. But I keep getting this error Error: connect ECONNREFUSED 127.0.0.1:5432 when trying to open localhost:8000/todos - not sure why.. I changed the username to 'postgres' (which is the defualt username), password, host, database name and port are all correct.. I can check the todos using SELECT * FROM todos; however, the app just breaks and gives me that code. I made sure that the server is running. I started it in services, and I can check the content of todos (which I manually added) in the SQL shell. Any ideas on why this is happening? I've gone thru all the other pages with similar issue, but I'm pretty new to postgreSQL overall and I'm unable to find an answer. I'm not using docker.
this is the exact error in the console:
Server runnnig on PORT 8080
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
main server.js
const PORT = 8080;
const express = require("express");
const app = express();
const pool = require("./db");
app.get("/todos", async (req, res) => {
try {
const todos = await pool.query("SELECT * FROM todos");
res.json(todos.rows);
} catch (err) {
console.error(err);
}
});
app.listen(PORT, () => console.log(`Server runnnig on PORT ${PORT}`));
db.js file where the connection is coming from
const Pool = require("pg").Pool;
require("dotenv").config();
const pool = new Pool({
user: "postgres",
password: process.env.PASSWORD,
host: "localhost",
port: 5432,
database: "todoapp",
});
module.exports = pool;

MongoTimeoutError: Server selection timed out after 10000 ms

I am trying to create a MERN app and containerize it with docker and manage the containers using kubernetes (minikube).
When I try to run the nodejs container it logs the following error
Server v8 up and running on port 5000 !
MongoTimeoutError: Server selection timed out after 10000 ms
at Timeout._onTimeout (/home/app/node_modules/mongodb-core/lib/sdam/topology.js:773:16)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
[Symbol(mongoErrorContextSymbol)]: {}
}
The code at server.js is as follows:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// the connection string when using username and password in mongodb-server
// mongodb://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}#mongodb-service:27017/exam?authSource=${process.env.MONGO_DB_USERNAME}
mongoose
.connect("mongodb://mongodb-service/exam", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log(`MongoDB successfully connected`))
.catch((err) => console.log(err));
The logs in mongodb container are as follows:
{"t":{"$date":"2022-12-16T14:28:58.316+00:00"},"s":"I", "c":"COMMAND", "id":51803, "ctx":"LogicalSessionCacheRefresh","msg":"Slow query","attr":{"type":"command","ns":"config.system.sessions","command":{"createIndexes":"system.sessions","v":2,"indexes":[{"key":{"lastUse":1},"name":"lsidTTLIndex","expireAfterSeconds":1800}],"ignoreUnknownIndexOptions":false,"writeConcern":{},"$db":"config"},"numYields":0,"reslen":114,"locks":{"ParallelBatchWriterMode":{"acquireCount":{"r":5}},"FeatureCompatibilityVersion":{"acquireCount":{"r":5,"w":1}},"ReplicationStateTransition":{"acquireCount":{"w":5}},"Global":{"acquireCount":{"r":5,"w":1}},"Database":{"acquireCount":{"r":4,"w":1}},"Collection":{"acquireCount":{"r":5,"w":1}},"Mutex":{"acquireCount":{"r":8}}},"storage":{},"protocol":"op_msg","durationMillis":529}}
If I should provide more details please tell me
Thanks in advance

Connect to MongoDB cluster

Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by "connect with the MongoDB shell", but this time I want to connect with the "connect your application" option.
When I hit mongosh in the embedded terminal in my mac, below was returned.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2
...
...
...
test>
Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.
Thanks for your time for dedication here. So appreciate it.
// this is db.js file in a config folder.
const mongoose = require('mongoose')
// It must be a promise function to connect db
const connectDB = async () => {
try {
console.log(`try`)
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'expense2'
});
console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
} catch (error) {
console.log(`Error: ${error.message}`.red)
process.exit(1);
}
}
module.exports = connectDB;
/*
Here is the error happened
Error: 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://docs.atlas.mongodb.com/security-whitelist/
[nodemon] app crashed - waiting for file changes before starting...
*/
config.env in the config folder as well.
NODE_ENV = development;
PORT=5000
MONGO_URI=mongodb+srv://mongo:mongo#cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&w=majority
// server.js file
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('colors');
const connectDB = require('./config/db')
dotenv.config({ path: "./config/config.env" })
connectDB();
const app = express();
const transactionsRouter = require('./routes/transactions')
app.use('/transactions', transactionsRouter)
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));

MongoNetworkError: failed to connect to server on first connect [MongoError: Authentication failed.]

I'm trying to connect to my MongoDB Atlas database, but it's not working, and I can't seem to figure out why.
I've made sure I don't use illegal characters in my username and password, I've tried different connection strings. I've tried turning off my firewall.
server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
const db = require("./keys").mongoURI;
mongoose.connect( db, { useNewUrlParser: true } )
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
keys.js
module.exports = {
mongoURI: "mongodb+srv://username:password#mernauth-lksvn.mongodb.net/test?retryWrites=true&w=majority"
};
I replaced the username and password in the connection string with the real username and password.
EDIT: SOLUTION
Even though I used both my IP address and the default IP address MongoDB Atlas suggested for me, neither worked. I guess I didn't have a valid IP address, so once I opened the database to all IP addresses, it worked!

Node/express application failing to connect to Mongodb Atlas using mongoose

I have a node/express application that I am trying to connect to Mongodb Atlas using mongoose.
All of my code is identical to a previous app that I had connect to Atlas (which worked fine). When I run it on my work machine (Windows 10) everything works as expected. However, when I run it on my MacBook Pro (Mojave), the express app runs but the mongoose connection to Atlas throws the following error:
{ Error: queryTxt EBADNAME development-zv5hp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
errno: 'EBADNAME',
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'development-zv5hp.mongodb.net' }
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose
.connect(
'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop',
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
What might be causing this issue?
I have checked the Atlas user and password and have whitelisted my IP (in fact whitelisted all IPs)
Using:
node v10.15.3
express v4.16.4
mongoose v5.5.1
Using Google's DNS server 8.8.8.8 and 8.8.4.4 can resolve this issue
please add autoIndex: false its working for me
mongoose
.connect(
'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop',
{autoIndex: false, useNewUrlParser: true }
This error is caused because the URI 'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop' that was passed to connect was unable to be resolved. Your DNS server does not know it and thus cannot resolve an IP. Hence ebadname.
change this like Addison mentioned

Resources