Mohammed Shahnawaz
Mohammed Shahnawaz

Reputation: 13

cannot read the property of "db" of null

I am learning Nodejs, but now I am getting this error

there is no more code accept this:

let express = require('express')
let mongodb = require('mongodb')
let server =  express()
let db

let connectionString = 'mongodb+srv://admin:******@cluster0-1vj27.mongodb.net/TodoApp?retryWrites=true'
mongodb.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
  db = client.db("TodoApp")
  server.listen(3000)
})

server.use(express.urlencoded({extended: false}))

server.get('/', function(req,res) {
    res.send(`....`)
})
server.post('/create-item', function(req, res) {
    db.collection('items').insertOne({text: req.body.item}, function() {
      res.send("Thank you submitting the form.")
    })
})

I am new to node, please help I am stuck. What should I do now please help

Upvotes: 0

Views: 36

Answers (1)

Léo Martin
Léo Martin

Reputation: 746

You must use mongodb.MongoClient, not mongodb directly :

const mongodb = require('mongodb');
const mongoClient = mongodb.MongoClient;

// connect

Find an example here : https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

Also, you should check if there is an error before trying to access client :

mongoClient.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
  if (err) {
    console.error(error);
    return;
  }
  db = client.db("TodoApp")
  server.listen(3000)
})

Upvotes: 1

Related Questions