最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何使用NodeJSexpress JS在MongoDB中获取文档数

IT培训 admin 4浏览 0评论

如何使用NodeJS / express JS在MongoDB中获取文档数

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

这是我正在尝试的内容:

//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:转换为ObjectId的值失败模型“发票”的路径“ _id”处的“ invoicescount”]

回答如下:

我正在使用此功能来获取每个集合的计数:

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

如何使用NodeJS / express JS在MongoDB中获取文档数

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

这是我正在尝试的内容:

//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:转换为ObjectId的值失败模型“发票”的路径“ _id”处的“ invoicescount”]

回答如下:

我正在使用此功能来获取每个集合的计数:

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);
});
发布评论

评论列表 (0)

  1. 暂无评论