简体   繁体   English

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

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

i have data in MongoDB and i want to return document count based on user input.But every time i am getting Count:0 even though i have document present in database matched to user input. 我在MongoDB中有数据,我想根据用户输入返回文档计数。但是,即使我数据库中存在与用户输入匹配的文档,每次我都得到Count:0

Below is my code kindly correct me what i am doing wrong: 下面是我的代码,请纠正我在做什么错:

 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);
   });

OUTPUT Count:0 输出计数:0

What you are doing is mixing 2 different commands collect.find({Name:obj}) and collect.count() . 您正在做的是混合使用2个不同的命令collect.find({Name:obj})collect.count() First command returns the array of documents based on your query, while the second one gives you the total count of documents in that particular collection and not the count of your queried documents. 第一个命令根据您的查询返回文档数组,第二个命令给您特定集合中文档的总数,而not查询的文档数。 What you are aiming can simply be achieved by: 您的目标可以通过以下方式轻松实现:

 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