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
Related
I have completed a project and trying to deploy on heroku. I am using Reactjs frontend and express Nodejs with mongoose and mongodb in the Backend. It works on localhost but when I run Build it and try to deploy it on heroku it gives an application error.
Here is my backend connection code:
require('dotenv').config();
const express = require('express')
const session = require("express-session")
const bodyParser = require('body-parser')
const cors = require('cors')
const zomatoRoutes = require('./Routes/zomato')
const paymentRoutes = require('./Routes/payments')
const mongoose = require('mongoose')
const passport = require("passport")
const MongoStore = require('connect-mongo');
const uri = process.env.MONGO_URI || 'mongodb://localhost/zomato';
console.log(uri,'this is the mongo Atlas uri if connected using that !!!')
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName:'zomato1'
}
const connectDB = async () => {
await mongoose.connect(uri, options ).then(() => {
console.log('mongo connected')
}).catch( e => console.log(e))
}
connectDB().then(() => {
app.listen( process.env.PORT ||5252 , () => {
console.log("express app is up and running on port 5252");
})
})
I also have mongo session store the mongoose session when user logs in
app.use(session({
secret: "this is unambigous secret",
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24*60*60*1000 },
store : MongoStore.create({
client: mongoose.connection.getClient(),
dbName:'zomato1',
ttl: 14 * 24 * 60 * 60
})
}));
app.use(passport.initialize());
app.use(passport.session());
It gives me MongoNotConnectedError: MongoClient must be connected to perform this operation error when I try to deploy using
git push heroku master:main
full error tail :
mongodb+srv://vishal_torne_22:********#db-first-hernode.zu6btrs.mongodb.net/<DBNamecomeshere>?retryWrites=true&w=majority this is the mongo Atlas uri if connected using that !!!
2022-07-31T11:19:34.581869+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:367
2022-07-31T11:19:34.581876+00:00 app[web.1]: throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
2022-07-31T11:19:34.581877+00:00 app[web.1]: ^
2022-07-31T11:19:34.581877+00:00 app[web.1]:
2022-07-31T11:19:34.581878+00:00 app[web.1]: MongoNotConnectedError: MongoClient must be connected to perform this operation
2022-07-31T11:19:34.581878+00:00 app[web.1]: at getTopology (/app/node_modules/mongodb/lib/utils.js:367:11)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at Collection.createIndex (/app/node_modules/mongodb/lib/collection.js:258:82)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at MongoStore.setAutoRemove (/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:147:35)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at /app/node_modules/connect-mongo/build/main/lib/MongoStore.js:128:24
2022-07-31T11:19:34.581882+00:00 app[web.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-07-31T11:19:34.581882+00:00 app[web.1]:
2022-07-31T11:19:34.581882+00:00 app[web.1]: Node.js v17.9.1
2022-07-31T11:19:34.703486+00:00 heroku[web.1]: Process exited with status 1
2022-07-31T11:19:34.791551+00:00 heroku[web.1]: State changed from starting to crashed
I am using Mongoose to connect the Mongodb, It works on localhost without heroku but when I deploy it using heroku, It asks me to use MongoClient. Is it a requirement to use mongoClient on Heroku 20 stack, I also get warning to upgrade to new Heroku version, I tried to upgrade heroku using npm upgrade heroku to the specifed version it shows successful but again rolls back to heroku 20 stack.
here's what I tried but researching the previous answers :
I added on my mongodb atlas the whitelist 0.0.0.0/0 (includes you current IP address)
I tried to make the mongoose code async so that it connect firsts the database then app listens to the port.
changed the engine version so that it supports latest node and npm version on Heroku like:
{
"version": "1.0.0",
"engines": {
"node": "17.x",
"npm":"8.x"
}
}
Is it a requirement to use MongoClient on heroku 20 stack ? as the Error shows... and why it is showing error on Mongoose.connect()
Thanks in advance..!
As you say it runs fine in your local environment, the issue may be fixed by adding process.env.MONGO_URL to the config vars of your application, as the issue may originate when Heroku tries to connect to your MongoDB, but does not achieve this connection due to an invalid url that is stored in an env variable on your local device.
This is the first time I am deploying my nodejs app on heroku
but this doesn't work well and I am getting boot time error
Earlier timeout was set to 60 sec but then I increased it to 120 sec from Heroku settings but still I am getting timeout please help me out in this I have already wasted 2 days into it.
Error from heroku logs:
I am getting this error on heroku logs
index.js :
import {app} from './app.js';
import {connectDb} from './config/db.js';
import 'dotenv/config';
const PORT = process.env.PORT | 3000;
app.listen(PORT,'0.0.0.0', () => {
console.log(`server running at port ${PORT}`);
//as soon as app starts connect DB;
connectDb();
});
db.js
import mongoose from 'mongoose';
export const connectDb = () => {
mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(console.log('DB connection successful'))
.catch(error => {
console.error('DB connection Error');
console.log(error);
process.exit(1);
});
}
as you can see I have added console.log in both of these file to check if connect to port is successful and db connection is succesful.
And I am getting console log as follow
console log from index.js file:
Server running at port 'some random port from herkou'
console log from db.js file:
DB connection successful
as per console log everything seems fine (db connection and all) then why I am getting this boot timeout error. please help me.
Note: I am using mongoDB Atlas as my DB
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));
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
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