This worked for me
mongoose.connect(
`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@cluster0.adv0t.mongodb.net/${process.env.MONGO_DATABASE}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
Create a ".env" file (you need to install dotenv before this ) in the parent directory(if you choose a custom location, add the following).
require('dotenv').config({ path: '/custom/path/to/.env' }) //uses custom location
Otherwise, add this in the server.js/app.js the one that initiates server.
require('dotenv').config() //uses default location
In the ".env" file, define the user, password and database like this
MONGO_USER=uSerName
MONGO_PASS=p@sSW0rd
MONGO_DATABASE=myDatabase