javascript - 如何使用 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:模型“invoices”的路径“_id”处的值“invoicescount”转换为 ObjectId 失败
解决方案
我正在使用此函数来获取每个集合的计数:
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);
});
推荐阅读
- python - 根据键的最后一行过滤熊猫数据帧
- java - 如何在控制器的 url 中传递对象?
- javascript - 当无头模式为真时,puppeteer 不会转到 chrome://version
- intellij-idea - 在intellij中将日志语句包装在单行中
- google-chrome - pushsubscriptionchange 在 Edge、chrome、opera 和 firefox 中不起作用。谁能告诉我我做错了什么?
- azure-ad-b2c - 自助密码重置(嵌入式密码重置示例)不会使用用户已在电子邮件字段中输入的内容预填充电子邮件字段
- python - 如何根据数据框中的条件将元素保留在列表中?
- sql - 空表视图
- c# - 按钮多点单击问题 Xamarin.Forms
- c# - Qt 的 qChecksum 里面是什么?