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?
The MongoDB server has deprecated the count() function in favor of two separate functions, countDocuments() and estimatedDocumentCount() . DeprecationWarning: collection. count is deprecated, and will be removed in a future version.
DeprecationWarning errors are logged by the Node. js runtime when your code (or one of the dependencies in your code) calls a deprecated API. These warnings usually include a DEP deprecation code. They are logged using console. error and end up in your CloudWatch logs.
useUnifiedTopology: False by default. Set to true to opt in to using the MongoDB driver's new connection management engine. You should set this option to true , except for the unlikely case that it prevents you from maintaining a stable connection.
The unified topology is the first step in a paradigm shift away from a concept of “connecting” to a MongoDB deployment using a connect method. Consider for a moment what it means to be connected to a replica set: do we trigger this state when connected to a primary?
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.
The underlying mongodb driver has deprecated the .count() method.You should use .estimatedDocumentCount() or .countDocuments() instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With