首页 > 解决方案 > 获取 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>)

非常感谢任何帮助。提前致谢。

标签: node.jsmongodbexpress

解决方案


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

推荐阅读