server.js
const dotenv = require("dotenv");
const connectDatabase = require("./config/database");
const cloudinary = require("cloudinary");
// Handling uncaught errors
process.on("uncaughtException", (err) => {
console.log(`Error: $(err.message)`);
console.log("Shutting down server due to uncaught exception");
process.exit(1);
});
//config
dotenv.config({ path: "backend/config/config.env" });
//connecting to database
connectDatabase();
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const server = app.listen(process.env.PORT, () => {
console.log(`server is working on ${process.env.PORT}`);
});
//unhandled promise rejection
process.on("unhandledRejection", (err) => {
console.log(`Error: ${err.message}`);
console.log("Shutting down server due to unhandled promise rejection");
server.close(() => {
process.exit(1);
});
});
databse.js
const { connect } = require("net");
const connectDatabase = () => {
mongoose
.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((data) => {
console.log(`Mongodb connected with server ${data.connection.host}`);
});
};
module.exports = connectDatabase;
config.env
PORT=4000
DB_URI = "mongodb://localhost:27017/Ecommerce"
process.env.PORT is coming undefined instead of 4000. The same problem is coming for DB_URI and other process.env variables. If I write 4000 instead of process.env.PORT and “mongodb://localhost:27017/Ecommerce” instead of process.env.DB_URI it works fine. Below is the Error in my terminal.
server is working on undefined
Error: 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.
Shutting down server due to unhandled promise rejection
How can I resolve this issue?