admin管理员组

文章数量:1278853

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

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

Share Improve this question edited Sep 16, 2019 at 14:58 asked Jul 5, 2018 at 10:27 anonanon 3
  • 3 You never error check on connect – Vivick Commented Jul 5, 2018 at 10:30
  • console log the err. There must be a problem with the connection. – Samudra Deka Commented Jul 5, 2018 at 10:36
  • Did you try MongoClient.open() ? – Dananjaya Ariyasena Commented Jul 5, 2018 at 10:37
Add a ment  | 

3 Answers 3

Reset to default 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!

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



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/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.

本文标签: javascriptMongoDB Nodejs TypeError Cannot read property 39db39 of nullStack Overflow