【问题标题】:Collection.estimatedDocumentCount() not showing resultsCollection.estimatedDocumentCount() 未显示结果
【发布时间】:2021-08-30 00:07:42
【问题描述】:

美好的一天, 我正在使用 MEAN 堆栈创建一个社交媒体应用程序,其中将包含一个选项来列出您关注的用户,但是,根据 Collections.Find() 已被弃用,我使用 Colletions.estimatedDocumentCount() 以 JSON 格式列出用户(目前我正在使用邮递员对其进行测试)。

它显示了用户数量和您关注的用户数量,但是 JSON 中没有更多数据可显示。

这是我的功能。任何帮助将不胜感激

function getFollowTest(req,res){

var userId = req.user.sub;

if (req.params.id) {
    user.id = req.params.id;
}

var page = 1;
if (req.params.page) {
    page = req.params.page;
}

var itemsPerPage = 4;

Follow.estimatedDocumentCount({user:userId})
                        .populate({path: 'followed'})
                        .paginate(page, itemsPerPage, (err, follows, total)=>{
        if (err) return res.status(500).send({message:'Server error'});

        if (!follows) return res.status(404).send({message:'you are not following any user'});

        res.status(200).send({
            total: total,
            pages: Math.ceil(total/itemsPerPage),
            follows
        });
});

}

这是 Postman 中的样子:

【问题讨论】:

  • 你的问题是什么?我看到 API 返回结果。
  • 你好,它应该显示总数,多少页和以下(应该显示用户ID,姓名,姓氏电子邮件等)

标签: javascript node.js database mongodb


【解决方案1】:

您错误地使用了paginate()。

检查一下:

const getPagination = (page, size) => {
  const limit = size ? +size : 3;
  const offset = page ? page * limit : 0;

  return { limit, offset };
};


const getFollowTest = async (req, res) => {

  var userId = req.user.sub;

  if (req.params.id) {
    user.id = req.params.id;
  }

  var page = 1;
  if (req.params.page) {
    page = req.params.page;
  }
  var itemsPerPage = 4;

  const { limit, offset } = getPagination(page, itemsPerPage);

  const result = await Follow.paginate({ user: userId }, { offset, limit });

  res.status(200).send({
    totalItems: result.totalDocs,
    tutorials: result.docs,
    totalPages: result.totalPages,
    currentPage: result.page - 1,
  });
}

【讨论】:

  • 谢谢 Murat...我忘了提到当我运行我的代码时,终端会显示这个 (node:2633) DeprecationWarning: collection.count is deprecated, and will be removed in a future version .请改用 Collection.countDocuments 或 Collection.estimatedDocumentCount ,所以我认为问题在于 Forms.find() 不再起作用,我正在寻找替代方案。谢谢
  • @SecaidaDevStudent 我真的不明白你为什么要使用 find 和 count ?您不需要对结果进行分页吗?您可以复制并粘贴我的答案并查看结果吗..
  • 嗨 Murat ..这里的目标只是显示一个 JSON,其中包含我正在关注的人和正在关注我的人的 ID,所以这就是我在运行它时使用 find 的原因在控制台中,它表示不推荐使用 find 功能并建议使用计数,但您知道吗?我想通过在我的 mongoose.connect() 中添加一些额外的东西,现在我可以毫无问题地使用 collections.find()...谢谢你的帮助
猜你喜欢
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2016-03-03
  • 2019-01-02
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多