Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Node.js TypeError: Cannot read property 'db' of null

I'm making a DB for my project, but in this code:

function getallvideos(callback) {
  MongoClient.connect(url, function(err, client) {
    const db = client.db("cathub")
    db.collection("videos", function(err, collection) {
      collection.find().toArray(function(err, res) {
        callback(res)
      })
    })
    db.close()
  })
}

I get this error:

TypeError: Cannot read property 'db' of null

like image 290
Vista1nik Avatar asked Jul 05 '18 10:07

Vista1nik


1 Answers

As mentioned above, you need to log the connection error. Once you do this you'll have an idea what the connection problem is! Make sure also that the DB name is present in your URL!

function getallvideos(callback) {
     MongoClient.connect(url, function(err, client) {
           if (err) {
               console.error('An error occurred connecting to MongoDB: ', err);
           } else {
               const db = client.db("cathub")
               db.collection("videos", function (err, collection) {
                    collection.find().toArray(function(err, res) {
                                 callback(res)
                    })
               })
               db.close()
           }
     })
}

I'd also handle the error accessing the videos collection, it'll be best in the long run!

like image 125
Terry Lennox Avatar answered Sep 22 '22 17:09

Terry Lennox