I am trying to connect to atlas mongo db using node js. But getting the error TypeError: Cannot read property 'db' of null I have created the cluster at atlas and given complete rights to user aayushg and also created a db 'test'
index.js
const express = require('express') const bodyParser= require('body-parser') const app = express() app.use(bodyParser.urlencoded({extended: true})) const MongoClient = require('mongodb').MongoClient; // replace the uri string with your connection string. const url = "mongodb+srv://aayushg:<aayushg18>@cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority"; const client = new MongoClient(url, { useNewUrlParser: true }); client.connect((err, database) => { db = database.db("test") app.listen(3000, function () { }) app.get('/', (req, res) => { //res.send('PDP') res.sendFile(__dirname + '/index.html') }) app.post('/quotes', (req, res) => { db.collection('devices').save(req.body, (err, result) => { if (err) return console.log(err) console.log('saved to database') res.redirect('/') }) }) }) 