How to fix the ‘db.collection is not a function’ error when using MongoClient v3.0?

Sometimes, we want to fix the ‘db.collection is not a function’ error when using MongoClient v3.0.

In this article, we’ll look at how to fix the ‘db.collection is not a function’ error when using MongoClient v3.0.

How to fix the ‘db.collection is not a function’ error when using MongoClient v3.0?

To fix the ‘db.collection is not a function’ error when using MongoClient v3.0, we should use the client.db method to return the database handle.

For instance, we write

MongoClient.connect('mongodb://localhost', (err, client) => {
  if (err) {
    throw err;
  }

  const db = client.db('mytestingdb');

  db.collection('customers').findOne({}, (findErr, result) => {
    if (findErr) {
      throw findErr;
    }
    console.log(result.name);
    client.close();
  });
});

to call MongoClient.connect to connect to our database.

In the callback we pass into connect, we get the client object, which we use to get the db handle with the client.db method.

Then we call db.collection to query the 'customers' collection.

The query results are in result.

Finally, we call client.close to close the database connection when we’re done.

Conclusion

To fix the ‘db.collection is not a function’ error when using MongoClient v3.0, we should use the client.db method to return the database handle.