On the Internet, the link to database and secret key are very important for the security of our database and the application as a whole. In any case, we need to keep them in our local machine not to expose them on GitHub or anywhere else. To hide them, we could create environment variables representing those secret key and password in a file called “.env” in the root folder, and we will only use those variable in the application. 

 

// .env

SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DATABASE_URI=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 

The SECRET_KEY could be anything we want because it could be considered as a password. As for DATABASE_URI, it is the link to our MongoDB database on MongoDB Atlas platform. If you did not signup with this platform yet, go ahead to create an account, and use the link to you database here, you can store your data up to 512 MB. It means that you can store millions of items on the web for free.

 

To use these environment variables in our application, we need to install dotenv package and mongodb driver.

 

npm install mongodb 
npm install dotenv

 

We should write the code as below to connect our application to MondoDB Atlas database.

 

// model/conMongoDB.js
// npm install mongodb
// npm install dotenv
 
import {MongoClient} from 'mongodb'
import dotenv from 'dotenv'
dotenv.config()

const url = process.env.DATABASE_URI
 
let resultPromise = new Promise(function(resolve,reject){
    MongoClient.connect(url, {useUnifiedTopology:true}, function(err, db){
        if (err) throw err
        const mydb = db.db("job")
        if(mydb){
            resolve(mydb)
            console.log('Connected to the main database!!')
        }else{
            reject("Error occured!")
        }
    })
})
 
async function awaitPromise(){
    let mydb = await resultPromise
    return mydb
}
 
export default awaitPromise()

 

// index.js
// npm install express

import express from 'express'
const app = express()

const port = process.env.PORT || 8000

import mydb from './model/conMongoDB.js'

app.use('/',async function(req,res,next){
    req.mydb = await mydb
    next()
})

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`This app is listening to the port ${port}`)
})

 

When we run the above application and we see the message “Connected to the main database!!” on Terminal window, it means that the connection to the database using environment variables is successful.