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'))
Related
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?
enter image description here I need to know what's the problem. I am not getting the message on console for establishment of Mongodb database connection.
Here is a link to the error picture. https://drive.google.com/file/d/14cdAgAjfVX6R7pXND-FbjbK_3r-A3F-J/view?usp=share_link
server.js file
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
// debugger
var uri; // Define outside
if(process.env.ATLAS_URI){
uri = process.env.ATLAS_URI; // Assign inside the block
}
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, ()=> {
console.log(`Server is running on port: ${port}`);
});
.env file
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
I tried to debug the code and found that uri was coming as undefined. Do I need to convert the password in ATLAS_URI to some other format?
The .env file must be located in the root folder of your project. And you should run the project from the root folder. Therefore:
Example 1
server.js
.env
Run it with node ./server.js
Example 2
src
|-server.js
.env
Run it with node ./src/server.js
You did one mistake in .env file
you did
ATLAS_URI = mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority
But you have to use url of atlas as an string
ATLAS_URI = "mongodb+srv://tripsy25:Mongo#123#cluster0.lwpkrde.mongodb.net/?retryWrites=true&w=majority"
The .env file must be located on the root folder and you must include it in the file where ever you need it at the very top.
and a few changings you just need to do and the things are good to go.
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
const app = express();
const port = process.env.port || 5000;
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.ATLAS_URI)
.then(() => {
console.log("DB connection successful")
app.listen(port, () => {
console.log(`app listening on port ${port}`);
})
})
.catch((err) => {
console.log(err)
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
I am not getting why you just create a var for ATLAS_URI. Just keep the code simple and neat and clean.
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.
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);
})
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