5

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

3
  • 3
    You never error check on connect Commented Jul 5, 2018 at 10:30
  • console log the err. There must be a problem with the connection. Commented Jul 5, 2018 at 10:36
  • Did you try MongoClient.open() ? Commented Jul 5, 2018 at 10:37

3 Answers 3

6

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!

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

Comments

0
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)
    })



2 Comments

Hi and welcome to the StackOverFlow, Please provide minimum detail about your code. For instance, what was the problem? or why your answer can tackle this issue.
Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users with similar issues.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.