@aphong what do you actually intend to do? Set up a connection with your database? or is it something else? Can you please share your code as well?
Thanks,
Kush
Hey! Bro, I just want to get infor from an API then save it into a database.
I have just figured it out the issue. It s weird that the file containing MongoDB connection does not read the .env file where I put the connection string inside & call it by this variable process.env.MOGNGO_CONNECTION_STRING despite that i have installed “dotenv” package & called this line require(“dotenv”).config();
Anyway! thank you so much bro!
I will get back to you regarding this issue, until then feel free to use the following method:
To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:
This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.
I hope this helps you until I get back to you with the .env solution.
thanks for your great code snippet. I got it!
Its just weird with the .env file. I put the .env file in the same directory with package.json & src folder. then I ve got index.js & bd.js where I call the mongodb connection inside the src folder.
├── src/ (… ,db.js , index.js)
├── node_modules
├── .env
└── package.json
Then the error appears when i try to run node index.js inside src folder.
if I replace the process.env.MOGNGO_CONNECTION_STRING variable by this url string ‘mongodb+srv://todoAppUser:@cluster0.6lvjr.mongodb.net/’ inside db.js file then the error is gone!
In my case I believe the issue was caused happening because of a small delay before the .env gets initiated.
If i call new MongoClient at the top of the module it fails, but if I call new MongoClient inside on a function I don’t get the issue.