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

2

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?

Naphthol answered 3/7, 2018 at 3:11 Comment(2)
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()Jewry
of course it's a right syntax. You can test it in mongo shell.Naphthol
F
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.

Filmer answered 3/7, 2018 at 7:23 Comment(2)
Which one matches the original .count ? It's .countDocuments right?Charin
@Charin it’s the estimatedDocumentCount()Filmer
A
5

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

Abbess answered 4/7, 2019 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.