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
Related
I setup a cluster in my mongodb atlas database and to my best of knowledge i did everything right and copied the right to my application using sample_mflix database
in my .env file
MOVIEREVIEWS_DB_URI=mongodb+srv://driiisdev:password123#cluster1.ektx7.mongodb.net/sample_mflix?retryWrites=true&w=majority
PORT=5000 //starting port of server
in my index.js file
import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"
dotenv.config();
const uri = process.env.MOVIEREVIEWS_DB_URI;
const client = new mongodb.MongoClient(uri);
const port = process.env.PORT||8000;
(async ()=>{
try{
//Connect to the MongoDB cluster
await client.connect();
app.listen(port, ()=>{
console.log("server is running on port:" +port);
})
}catch(e){
console.error(e);
process.exit(1)
}
})().catch(console.error);
in my server.js
import express from 'express'
import cors from 'cors'
import movies from './api/movies.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/movies", movies)
app.use('*', (req,res)=>{
res.status(404).json({error:"not found"})
})
export default app
on running nodemon server , the error i get
Error: querySrv ECONNREFUSED _mongodb._tcp.cluster1.ektx7.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:213:19) {
errno: undefined,
code: 'ECONNREFUSED',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster1.ektx7.mongodb.net'
}
The error indicates a possible SRV lookup failure.
Could you try using the connection string from the connection modal that specifies all 3 hostnames instead of the SRV record? To get this, please head to the Atlas UI within the Clusters section and follow the below steps:
Click Connect on the cluster you wish to connect to
Select Connect your application
Choose Node.JS for the Driver option
Choose the *Version 2.2.12 or later for the version option
Copy and use the connection string which should begin with the following format:
mongodb://:....
Replace the original connection string you used with the version 2.2.12 or later node.js connection string copied from the above steps and then restart your application.
//also in the .env file
// remove the comment after the PORT is assigned, as .env reads comment and will return error
PORT=5000
I am building A MERN stack app on linux. The internet only work when we use proxy server of college. I am using mongoose for creating connection with MongoDB Atlas. The issue is that mongoose is unable to connect to MongoDB although i already set the proxy. How can I create connection in mongoose through university proxy server with MongoDB Atlas.
Currently mongoose connection is setup like this:
const CONNECTION_URL =process.env.CLUSTER_URL;
const PORT = process.env.PORT || 3000;
mongoose
.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() =>
app.listen(PORT, () => {
console.log(`server running at PORT ${PORT}`);
}),
)
.catch(error => console.log(error));
Currently university is using HTTP_PROXY=http://172.16.100.7:3022.
Error: UnhandledPromiseRejectionWarning: 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://docs.atlas.mongodb.com/security-whitelist/
Things I've tried:
Whitelisting all IP addresses under security, inside of my mongo db atlas, by setting a catchall IP address: 0.0.0.0/0
Whitelisting my specific IP address
Changing my password, and making is super insecure and adding it directly to the uri string, to make sure that it's not a credentials issue.
Commenting all other lines of code to test the uri string only.
Using the default port number 3000
My Index.js file
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// CORE MIDDLEWARE
app.use(express.static('public'));
// CUSTOM MIDDLEWARE
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// MONGO/MONGOOSE
mongoose.connect
(`mongodb+srv://myUsername:MyPassword#ClusterName.id9lz.mongodb.net/database-
name?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
const port = 5000 || process.env.PORT;
app.listen(port, () => {
console.log(`Listening to port ${port}...`)
})
NOTE: I've cut out all excess code like dependencies, etc, out of this question, so it's easier to parse through and find an answer faster. I'm completely out of ideas. I don't know what else to even attempt. Thank you in advance
This has happened to me before, i don't know why really, but, after 2 hours, it started to work correctly again, the only thing that comes to my mind is that my internet was kinda weak... But i really don't know why was that happening anyways.
But, you should try to change the way you want to connect your server to mongoDB, i used to do it like that, but after a while, i've had some problems.
So, try to change it like this
const port = 5000 || process.env.PORT;
mongoose.connect
(`mongodb+srv://myUsername:MyPassword#ClusterName.id9lz.mongodb.net/database-
name?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
app.listen(port, () => {
console.log(`Listening to port ${port}...`)
})
console.log('MongoDB connected correctly')
})
And also, make sure you're credentials are correct while trying to connect to MongoDB
Hope i helped you a litle bit !
I am getting the below error in the terminal:
Error: querySrv ECONNREFUSED _mongodb._tcp.cluster0.vxgqt.mongodb.net did not connect
on running the index.js file
It was working fine till yesterday and today on running it is giving this error.
This is the code snippet:
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL = 'mongodb+srv://<username>:<password>#cluster0.vxgqt.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
NOTE: I have provided the correct username and password in the connection url
I found a temporary fix and that is working: Under connect your application in MongoDB Atlas I selected node version 2.2.12 or later instead of 3.6 or later(which I used earlier). By selecting this, the application is now working fine as before
First of all check your internet connection and then go to mongodb Atlas and check whether your ip address is available in whitelist or not.
for testing purpose allow all ip's to access and then connect again.
querySrv ECONNREFUSED means that the attempt to resolve the SRV record failed to connect to a name server.
This is a DNS problem. Your application will need to be able to resolve the SRV record for _mongodb._tcp.cluster0.vxgqt.mongodb.net in order to use the mongodb+srv connection string.
you need to write your username and password inside URI of mongoDB, that mean u need to take value of CONNECTION_URL constant variable and change to current username of your account on mongoDB and change to current password of your account on mongoDB
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
errno: 'ETIMEOUT',
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'scheduly.1eln0.mongodb.net'
}
I’m facing the above connection Error while connecting with MongoDB Atlas. I’ve double-checked my username and password. I’ve whitelisted all the IP’s. I’m stuck in the middle of a project and cannot connect to the DB itself.
my connection strings are:
const mongoose = require("mongoose");
const mongodb = require("mongodb");
const uri = "mongodb+srv://ghulamghousdev:***********#scheduly.1eln0.mongodb.net/scheduly?retryWrites=true&w=majority
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected");
})
.catch((err) => console.log(err));
The name of the Database on MongoDB atlas is scheduly.
Have you tried to add the ip of your VPS, host to the IP Whitelist of Network access?
You can see more details for that setting from here https://docs.atlas.mongodb.com/security-whitelist/