Click ⭐if you like the project. Pull Requests are highly appreciated. Follow me BappaSaha for technical updates.
-
- nodemon globally install
- mongodb atlas user, access
- Network access (ip address allow)
-
- install mongodb, express, cors, dotenv
- import (require), mongodb
- copy uri (connection string)
- create the client (copy code from atlas)
- Create or get database access credentials (username, password)
- create .env file and add DB_USER and DB_PASS as environment variable
- Make sure you require (import) dotenv
- Convert URI string to a template string.
- Add DB_USER and DB_PASS in the connection URI string.
- Check URI string by using console.log
- Create async function run and call it by using run().catch(console.dir)
- add try and finally inside the run function.
- comment out await client.close() to keep the connection alive
- add await client.connect(); inside the try block
- use a console.log after the client.connect to ensure database is connected
const express = require('express') const { MongoClient } = require('mongodb'); require('dotenv').config() const app = express() const port = process.env.PORT || 5000; const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.swu9d.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`; console.log(uri); const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); async function run() { try { await client.connect(); console.log('database connected'); } finally { // await client.close() } } run().catch(console.dir); app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) }) ```