node.js - 获取 mongodb 中的文档总数
问题描述
我是 mongodb 的新手,并试图从集合中获取记录总数。我正在使用节点快递。
我的代码 -
let mongoose = require('mongoose');
let Patient = require('../models/patient');
/*
* GET /patient route to retrieve all the patients.
*/
function getPatients(req, res) {
let page = Number(req.params.page);
let pageSize = Number(req.params.pageSize);
let start = (page-1)*pageSize;
//Query the DB and if no errors, send all the patients
let total = Patient.count({});
//console.log(total);
let query = Patient.find({});
query.skip(start);
query.limit(pageSize);
query.exec((err, patients) => {
if(err) res.send(err);
//If no errors, send them back to the client
res.json({total:total, page:page, pageSize:pageSize, items:patients});
});
}
我得到的错误信息是——
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
非常感谢任何帮助。提前致谢。
解决方案
mongoose count 是一个异步函数(返回一个 Promise),也可以与回调一起使用。
您的错误必须与res.json
承诺相关,而不是其结果本身。
这是一个使用 Promise 的解决方案(异步/等待语法):
async function getPatients(req, res) {
let page = Number(req.params.page);
let pageSize = Number(req.params.pageSize);
let start = (page-1)*pageSize;
//Query the DB and if no errors, send all the patients
let total = await Patient.count({});
console.log(total); // will log the real count
let query = Patient.find({});
query.skip(start);
query.limit(pageSize);
query.exec((err, patients) => {
if(err) res.send(err);
//If no errors, send them back to the client
res.json({total:total, page:page, pageSize:pageSize, items:patients});
});
}
您当然也可以在count
函数上使用回调:
Patient.count({}, (error, count) => {
if(error) res.send(error);
// work with total
});
推荐阅读
- swift - Swift 5.2 中的 iTunes 库框架
- imagemagick - 为什么将 CMYK 图像转换为 sRGB 以在 Web 上显示在本地工作,而不是在 prod 服务器上?
- ember.js - 我可以在两个 EmberJS 应用程序之间共享状态吗
- node.js - Nextjs 和 Express 作为中间件。如何将 'localhost:3000/newpage' 和 'localhost:3000/newpage/' 设置为相同的路由
- azure-devops - Azure DevOps Release Pipeline Managed Identity App Service 部署时出错
- function - 为什么 Rust 编译器不够聪明,无法检测同名的变量和函数?
- angular - 在 Angular 中的条件下显示选择选项
- python - 在时间列上进行分组并仅总结唯一值
- azure - AZURE FHIR:_lastUpdated 如何转换为 ResourceSurrogateId
- c# - 如果它们之间存在依赖关系,MsBuild 是否会等到另一个由不同线程启动的 MsBuild 进程完成?