19

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?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Is this right syntax? I think you have problem in your query ,what is post inside bracket, if you want to count anything on field , first you need to find then count for ex:db.collectionName.find({filedName : filedValue}).count() – Mohammad Raheem Jul 03 '18 at 05:19
  • of course it's a right syntax. You can test it in mongo shell. – Lin Du Jul 03 '18 at 06:10

2 Answers2

34

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.

Wan B.
  • 18,367
  • 4
  • 54
  • 71
5

The underlying mongodb driver has deprecated the .count() method.You should use .estimatedDocumentCount() or .countDocuments() instead.

pranita mohite
  • 151
  • 1
  • 2
  • 3