// imports
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const app = express();
const PORT = process.env.PORT || 4000;
// database connection
mongoose.connect(process.env.DB_UR);
const db = mongoose.connection;
db.on("error", (error) => console.log(error));
db.once("open", () => console.log("Connected to the database!"));
// middlewares
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(session({
secret: 'my secret key',
saveUninitialized: true,
resave: false,
}));
app.use((req, res, next) => {
res.locals.message = req.session.message;
delete req.session.message;
next();
});
// set template engine
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(PORT, () => {
console.log(`Server started at http://localhost:${PORT}`);
});
``
this raises an error message of Connection error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017.
I have tried all ways to troubleshoot this as suggested on every platforms. I tried la restarting the mongodb in the services, adding the bin path to the environment variable, uninstall and reinstalling mongodb, etc… Nothing worked. I’ve used MongoDB Compass to create the database.