简体   繁体   中英

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

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:yourPassword@yourCluster.mongodb.net/'
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)
    })



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM