my app.js file has code :
const connectDB = require("./db/connect");
require("dotenv").config()
const app = express();
const url = process.env.MONGO_URI;
const port = 8080;
// listen to server
const start =async () =>{
try {
await connectDB(url);
app.listen(port, () => {
console.log("Connected To DB + App is listening on http://localhost:${port}");
});
} catch (error) {
console.log(error);
}
};
// call the start function
start();
my connect.js file has code :
mongoose.set('strictQuery', true);
const connectDB = (url)=>{
return mongoose.connect(url)
}
module.exports = connectDB;
.env file has this variable :
MONGO_URI =mongodb+srv://<username>:<password>@cluster0.prrizft.mongodb.net/TaskManager?retryWrites=true&w=majority
In the above string I am using the correct username and password.
Also I have already add the ip in network (both : from anywhere and my current ip).
I can able to successfully connect the above string with mongo compass (plus I tested to create a dummy collection and insert document…. everything work fine)
But when I connect the mongoAtlas with node.js using mongoose I will get error[enter image description here](https://i.stack.imgur.com/Ir5BQ.png)
3
Answers
Using the ‘dotenv’ package requires initializing the library at the beginning of your script. This can be done in the npm start script or terminal:
Or if you must include within the code, require(‘dotenv’).config() should be called at the very top of your entry script as in the above:
So in your code example, replace:
With:
And this should solve process.env being in scope when connect.js is loaded.
within your mongoDB atlas…
in Network Access… edit IP access list
switch it to “allow access from anywhere”
Note: Please add below packages first
npm i express, npm i dotenv, npm i mongoose
**
**