2

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('/') }) }) }) 

SCREENSHOT OF CMD enter image description here

8
  • please add your terminal screen shot too Commented Oct 31, 2019 at 8:01
  • added the screenshot Commented Oct 31, 2019 at 8:03
  • I think you have no client Commented Oct 31, 2019 at 8:07
  • i tried with using client also but didnt work Commented Oct 31, 2019 at 8:08
  • i have updated my code Commented Oct 31, 2019 at 8:11

2 Answers 2

3

So, the error was related to the credentials you are providing with the help of if(err) throw err you can see the error is regarding the credentials. Now, you have to add correct credentials it will work fine. you are using <aayushg18> instead of aayushg18 Thanks.

Sign up to request clarification or add additional context in comments.

3 Comments

The error is in this line db = database.db("test") here databaseis null, there is problem in connection. But your answer states that problem lies if (err) return console.log(err) before that itself error in thrown.
nope there is error in credentials we have go through the chat :)
I have just updated my last line to make you understand, thanks
1

I have got your problem. You connection uri is not in correct format. Do not use <> sign when you input your password. Replace <aayushg18> by aayushg18 like following:

const uri = "mongodb+srv://aayushg:[email protected]/test?retryWrites=true&w=majority"; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.