anon
anon

Reputation:

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

Upvotes: 5

Views: 12796

Answers (3)

Kush Kapadia
Kush Kapadia

Reputation: 63

I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:

const {MongoClient} = require('mongodb')


const client = new MongoClient('mongodb+srv://todoAppUser:<password>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')

async function start(){
  await client.connect()
  console.log("Connected")
  module.exports = client.db()
  const app = require('./app')
  app.listen(3000)
}

  start()

and while calling it from another file:

const productCollection = require('./db').collection("product");

This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.

Upvotes: 0

m_r
m_r

Reputation: 1

const DB_URL = 'mongodb+srv://yourUser:[email protected]/'
const DB_NAME = 'someDBName'
const DB_COLLECTION_NAME = 'someCollectionName'


const getData = async () => {
    const client = await MongoClient.connect(DB_URL, {
        useUnifiedTopology: true
    }).catch((err) => {
        console.log(err)
    })

    if (!client) {
        return []
    }

    try {
        const db = client.db(DB_NAME)
        const collection = db.collection(DB_COLLECTION_NAME)
        const res = await collection.find().toArray()
        return res
        // console.log(res)
    } catch (err) {
        return err
        // console.log(err)
    } finally {
        client.close()
    }
}


getData()
    .then((data) => {
        console.log(data)

    })
    .catch((err) => {

        console.log(err)
    })



Upvotes: 0

Terry Lennox
Terry Lennox

Reputation: 30715

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!

Upvotes: 6

Related Questions