Reputation: 502
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('/')
})
})
})
Upvotes: 2
Views: 296
Reputation: 2280
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.
Upvotes: 3
Reputation: 1471
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";
Upvotes: 1