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