TypeError: db.collection is not a function

So I voted for the answer which said to just go down to mongodb 2.2.33 because I tried it and it worked, but then I felt weird about just downgrading to fix a problem so I found the solution which allows you to keep version >= 3.0. If anyone finds this issue and their problem wasn’t passing in a blank reference like the accepted answer, try this solution out.

When you run..

MongoClient.connect(db.url,(err,database) =>{ }

In mongodb version >= 3.0, That database variable is actually the parent object of the object you are trying to access with database.collection('whatever'). To access the correct object, you need to reference your database name, for me that was by doing

MongoClient.connect(db.url,(err,database) =>{ 
  const myAwesomeDB = database.db('myDatabaseNameAsAString')
  myAwesomeDB.collection('theCollectionIwantToAccess')
}

This fixed my errors when running my node.js server, hopefully this helps somebody who doesn’t just want to downgrade their version.

(also, if you don’t know your db name for some reason, just do a console.log(database) and you’ll see it as an object attribute)


EDIT (June 2018):

According to this, the callback actually returns the connected client of the database, instead of the database itself.

Therefore, to get the database instance, we need to use this method, which takes in a dbName. In the documentation it said If not provided, use database name from connection string., as mentioned by @divillysausages in the comments below.

In short, we should call database.db().collection('theCollectionIwantToAccess'); if the dbName is provided by url, where the database is actually client for better understanding

Leave a Comment