【问题标题】:How to get count of no. of documents available in MongoDb using NodeJs如何计算没有。使用 NodeJs 在 MongoDb 中可用的文档
【发布时间】:2020-01-28 08:19:24
【问题描述】:

我正在尝试使用 NodeJS 获取我的集合中可用的文档数量。我在控制台中成功获取了号码,但它没有发送响应并显示以下错误:

RangeError [ERR_HTTP_INVALID_STATUS_CODE]:无效状态代码:10 在 ServerResponse.writeHead (_http_server.js:246:11) 在 ServerResponse._implicitHeader (_http_server.js:237:8) 在 ServerResponse.end (_http_outgoing.js:720:10) 在 ServerResponse.send (D:\Backend\aamku_con_backend\node_modules\express\lib\response.js:221:10) 在 D:\Backend\aamku_con_backend\routes\dealerCount.js:29:50 在 executeCallback (D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\execute_operation.js:74:5) 在 callbackWithRetry (D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\execute_operation.js:122:14) 在 D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\count_documents.js:36:7 在 D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\command_v2.js:90:9 在 D:\Backend\aamku_con_backend\node_modules\mongodb\lib\cmap\connection_pool.js:308:13 { 代码:'ERR_HTTP_INVALID_STATUS_CODE'

下面是我的代码:

router.get("/dealerCount", (req, res) => {        
  MongoClient.connect(dburl,{ useNewUrlParser: true, useUnifiedTopology: true },
    (err, client) => {
      if (err) {
        console.log("Error", err);
      } else {
        const coll = client.db("Mydb").collection("Dealers");

        coll.countDocuments(function(err, resp) {
          if (err) {
            console.log("Error", err);
          } else {
            console.log(resp);
            res.send(resp);
          }
        });
      }
    }
  );
});

请让我知道如何获得总计数作为回应。任何帮助将不胜感激。

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    问题是res.send(resp); 行。它使 express 认为您正在发送一个不允许的整数。用这个替换它

    res.send({"value": resp});
    
    OR
    
    res.send(resp.toString());
    

    【讨论】:

    • 谢谢,我忘了把它转换成字符串,现在它工作正常了。
    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 2021-08-15
    • 2012-02-17
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    相关资源
    最近更新 更多