簡體   English   中英

如何計算不。 Node.Js在MongoDB集合中收集文檔?

[英]How to count no. of documents in MongoDB collection using Node.Js ?

我在MongoDB中有數據,我想根據用戶輸入返回文檔計數。但是,即使我數據庫中存在與用戶輸入匹配的文檔,每次我都得到Count:0

下面是我的代碼,請糾正我在做什么錯:

 const express = require('express');
 const bodyParser = require('body-parser');
 const mongoClient = require("mongodb").mongoClient;

 var app = express();
 var port = process.env.PORT || 3000;
 var url = "http://localhost:3000/";

 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({extended:true}));

 app.post('/finish',(req,res) =>{

 mongoClient.connect(url,(err,db) => {

           if(err){
              console.log("Error:" +err);
            }

          else{

             var obj = {Name:req.body.name};

             var collect = db.db("Tiffino").collection("Users"); 

             var cnt = collect.find({Name:obj}).count.then((count)=>{

                   console.log("Count:" +count);
               }); 

            }
    }); 

 });

  app.listen(port,(req,res) => {

        console.log("App is running at:" +port);
   });

輸出計數:0

您正在做的是混合使用2個不同的命令collect.find({Name:obj})collect.count() 第一個命令根據您的查詢返回文檔數組,第二個命令給您特定集合中文檔的總數,而not查詢的文檔數。 您的目標可以通過以下方式輕松實現:

 collect.find({Name:obj}).then((docs)=>{ console.log("Count:" docs.length); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM