mongodb-nodejs-driver, DeprecationWarning: collection.count is deprecated

slideshowp2 picture slideshowp2 · Jul 3, 2018 · Viewed 17.5k times · Source

I want to get the count of posts documents using:

db.collection('posts').count()

But, I got a warning:

DeprecationWarning: collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead

Here is my mongodb nodejs driver version:

  "dependencies": {
    "mongodb": "^3.1.0"
  },
  "devDependencies": {
    "@types/mongodb": "^3.1.0",
    "chai": "^4.1.2",
    "mocha": "^5.1.1",
    "ts-node": "^7.0.0",
    "tslint": "^5.10.0",
    "typescript": "^2.9.2"
  }

There is no countDocuments or estimatedDocumentCount in index.d.ts file.

How can I solve this warning?

Answer

Wan Bachtiar picture Wan Bachtiar · Jul 3, 2018

As you figured out, starting from MongoDB Node.JS driver v3.1 the count() method has been deprecated and will be replaced with :

These methods have been added to node-mongodb-native package itself. For example, via the MongoDB Node.JS driver you should be able to do:

db.collection("posts").countDocuments(
  {}, // filters
  {}, // options
  function(error, result) {
    console.log(result);
  }
);

See also NODE-1501

There is no countDocuments or estimatedDocumentCount in index.d.ts file.

This is because the TypeScript definitions for the mongodb npm package has not been updated to include the two new methods. The list of types is actually maintained separately by community via DefinitelyTyped (GitHub: DefinitelyTyped)

I have submitted a pull request DefinitelyTyped #27008 to add the new methods. Once approved and published you should be able to see the typed definitions.