mongodb-nodejs-driver,弃用警告:collection.count 已弃用

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

我想使用以下方式获取帖子文档的数量:

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

但是,我收到警告:

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

这是我的 mongodb nodejs 驱动程序版本:

  "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"
  }

index.d.ts 文件中没有 countDocumentsestimatedDocumentCount

如何解决这个警告?

如您所知,从 MongoDB Node.JS driver v3.1 开始,count() 方法已被弃用,将被替换为:

这些方法已添加到 node-mongodb-native 包本身。例如,通过 MongoDB Node.JS 驱动程序你应该能够做到:

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

另见 NODE-1501

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

这是因为 mongodb npm 包的 TypeScript 定义尚未更新以包含这两个新方法。类型列表实际上由社区通过 DefinitelyTyped (GitHub: DefinitelyTyped)

单独维护

我已提交拉取请求 DefinitelyTyped #27008 以添加新方法。一旦获得批准并发布,您应该能够看到类型化的定义。

基础 mongodb 驱动程序已弃用 .count() method.You 应改用 .estimatedDocumentCount() 或 .countDocuments()。