【问题标题】:How to get the document count in MongoDB using NodeJS/express JS如何使用 NodeJS/express JS 获取 MongoDB 中的文档数
【发布时间】:2019-10-05 11:28:02
【问题描述】:

我正在尝试获取 MongoDB 集合中 documents 的计数,但我没有得到计数。

这是我正在尝试的:

//get the invoice count
Routes.route('/invoicescount').get((req, res) => {
  invoicesDB.count({}, (err, count) => {
    if (err) {
      res.status(400).send(err);
    } else {
      const c = count;
      res.status(200).send(c);
    }
  });
});

它没有给出任何值,但在控制台中它给出了这个错误:

发现错误:CastError: Cast to ObjectId failed for value 模型“invoices”的路径“_id”中的“invoicescount”

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    我正在使用这个函数来获取每个集合的计数:

    var MongoClient = require('mongodb').MongoClient;
    
    var dbName = "myName";
    var port = "27017";
    var host = "localhost";
    
    function getNumOfDocs (collectionName, host, port, dbName, callback) {
        MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
            if(error) return callback(error);
    
            db.collection(collectionName).count({}, function(error, numOfDocs){
                if(error) return callback(error);
    
                db.close();
                callback(null, numOfDocs);
            });
        }); 
    } 
    

    我称之为:

    getNumOfDocs("collName", host, port, dbName, function(err, count) {
       if (err) {
           return console.log(err.message);
       }
       console.log('number of documents', count);
    });
    

    【讨论】:

    • 我会试试这个并告诉你
    • 但是变量的名称、它应该如何被调用以及你在哪里使用它应该在你自己的代码中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2022-06-14
    • 2019-05-07
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多