I can not connect to Mongo db - node.js

Hello I work with Mongo db.
When I try to connect to Mongo he shows me the 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/
I allowed access from anywhere. But it's not working.
It is important to note that on other computers with other internet networks it does work for me.
My code is:
const express = require('express')
const app = express()
app.listen(3000, () => { console.log("listening") })
const router = require('./routes/api')
const dotenv = require('dotenv')
dotenv.config()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
const mongoose = require('mongoose')
app.use('/', router)
mongoose.connect(process.env.DB_CONNECT, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}).then(res=>{
console.log("DB Connected!")
}).catch(err => {
console.log(Error, err.message);
})

Related

How find endpoints of my heroku deployed nodejs app?

Below you can see my localhost nodejs api endpoint and its successfullyworking.
http://localhost:3000/api/user/login/
But after I deployed app in Heroku I cannot call that endpoint.
After deployed in the heroku I tried with this url
https://employee-management-app-001.herokuapp.com/api/user/login
Below you can see my server file
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const port = process.env.PORT || 3000;
const uri = 'mongodb+srv://user1:1234#cluster0.pkiw6x0.mongodb.net/comp3123_assignment1'
//const jwt =require('jsonwebtoken');
var cors = require('cors')
app.use(cors())
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Successfully connected to the database mongoDB Atlas Server");
}).catch(err => {
console.log('Could not connect to the database.', err);
process.exit();
});
app.use(express.json())
const usersRouter = require('./routes/users')
app.use('/api/user',usersRouter)
const employeesRouter = require('./routes/employees')
app.use('/api/emp',employeesRouter)
mongoose.connect(uri)
app.listen(port,()=> console.log("Server Started on Port "+port))
Can anyone helop me to solve thiss issue?

Mongo DB not connecting to NodeJS after Heroku deployment

I've a MERN app (Mongo Express React Node) that works locally, and connects to my MongoDB database, getting data.
The React front-end works after I deploy it to Heroku, but Nodejs won't connect to MongoDB on Heroku.
The environment variables like MONGO_URI stored as Heroku config variables, works perfectly fine, yet it just won't connect to my MongoDB.
The Heroku logs shows the error message: DISCONNECTED FROM MONGO DB from my server.js file.
How can I solve this?
server.js file
const express = require("express");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");
dotenv.config();
const authRouter = require("./routes/auth");
const blogRouter = require("./routes/blog");
const userRouter = require("./routes/user");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use("/api/auth", authRouter);
app.use("/api/user", userRouter);
app.use("/api/blog", blogRouter);
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const connect = () => {
mongoose
.connect(process.env.MONGO_URL,
{useNewUrlParser: true,
useUnifiedTopology: true,
useNewUrlParser: true})
.then(() => {
console.log("CONNECTED TO THE MONGO DB");
})
.catch((err) => {
console.log(err);
mongoose.disconnect(() => {
console.log("DISCONNECTED FROM MONGO DB");
});
})
};
app.listen(process.env.PORT || 8000, () => {
connect();
console.log("MONGO_URL", process.env.MONGO_URL);
console.log("PASSCODE", process.env.PASSCODE);
console.log(`LISTENING ON PORT ${process.env.PORT}`);
})
Your environment variable to connect to MongoDB database has to be MONGO_URI, not MONGO_URL.
Otherwise it won't work.

Cannot connect to database The `uri` parameter to `openUri()` must be a string, got "undefined"

I am trying to deploy my node backend on heroku but I am facing the error that :-
Cannot connect to database The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
Everything is working fine in the development mode, my mongo atlas database is being connected and all routes are working fine but as I switched to production, heroku cannot connect to my database.
My server code is :-
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const fileUpload = require("express-fileupload");
const cookieParser = require("cookie-parser");
const users = require("./routers/users");
const category = require("./routers/category");
const products = require("./routers/product");
const uploadImages = require("./routers/upload");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use(
fileUpload({
useTempFiles: true,
})
);
// connecting to MongoDB
const mongoURL = process.env.MONGO_URL;
mongoose
.connect(mongoURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => console.log("DataBase has been connected !"))
.catch((err) => console.log("Cannot connect to database", err.message));
// routes
app.use("/users", users);
app.use("/category", category);
app.use("/images", uploadImages);
app.use("/products", products);
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`I am listening at ${port}`);
});
I had added my .env file which includes my mongo connection url string, in my .gitignore file. Due to this, Heroku wasn't able to read my connection string and the logs were giving the url undefined. I just removed the lines in the .gitignore that were ignoring the .env file and Heroku was able to connect to my mongo atlas database

nodejs connection fail to database

i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);

nodejs cant connect to mongodb using mongoose

so all my applications were working just fine using mongoose, all of a sudden they all stopped. i cant connect to my database. however my deployed apps using mongoose databases work fine, but i cant access to any database using my local computer. here is a test server ive written. can someone help me whats happening.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const app = express();
app.use(express.json())
const db = require('./keys').mongoURI;
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('connected'))
.catch(err => console.log(err))
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server running'))
module.exports = {
mongoURI: 'mongodb+srv://ertemishakk:<password>#cluster0-xi4zx.mongodb.net/test?retryWrites=true&w=majority'
}
Terminal:
server running
MongoTimeoutError: Server selection timed out after 30000 ms
at Timeout._onTimeout (/Users/ishakertem/Desktop/test/node_modules/mongodb/lib/core/sdam/server_selection.js:308:9)
at listOnTimeout (internal/timers.js:536:17)
at processTimers (internal/timers.js:480:7) {
name: 'MongoTimeoutError',
}
You should check your
bindIp : [public_ip]
option in
mongod.conf
file.
It should be pointed out to public IP of that system on which MongoDB is running.
You can use 0.0.0.0 for debuging only, because it is exposed One.
[DO VOTE TO THIS ANSWER, IF ITS HELPFUL TO YOU]
You Can Follow This Code I hope solved your problem
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const app = express();
app.use(express.json())
//Remove <password> and provide DB password
/**
* Example: mongodb + srv: //ertemishakk:123#cluster0-xi4zx.mongodb.net/test?retryWrites=true&w=majorit
*/
mongoose.connect('mongodb+srv://ertemishakk:<password>#cluster0-xi4zx.mongodb.net/test?retryWrites=true&w=majorit', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('connected'))
.catch(err => console.log(err))
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server running'))

Resources