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@[email protected]/?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?
3
Answers
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
Run it with node
./server.js
Example 2
Run it with node
./src/server.js
You did one mistake in
.env
fileyou did
But you have to use
url
ofatlas
as an stringThe .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.
I am not getting why you just create a var for ATLAS_URI. Just keep the code simple and neat and clean.