【问题标题】:In mongo how to get the current position of the record in the table with the total records for pagination?在mongo中如何通过总记录获取表中记录的当前位置进行分页?
【发布时间】:2018-03-21 11:41:44
【问题描述】:

我正在尝试返回创建一个分页列表。我使用 graphql 来查询数据。通过我的查询,我传递了我需要的记录数(在一个名为 first 的变量中)和最后获取的记录的 ID(在一个名为 after 的变量中)。现在我设法编写了一个查询(注意我使用了mongoose)来获取记录。现在我需要做的是获取相关信息来执行分页,如hasNextPagehasPreviousPagecurrentPagetotalPages

要获取大部分这些信息,我需要获取数据库中的记录总数。为此,我需要发送另一个数据库请求。

我还需要知道记录在表中的位置。不知道怎么做。

这是查询:

new Promise((resolve, reject) =>
  Company.where('_id')
    .gt(after)
    .limit(first)
    .lean()
    .exec((error, doc) => {
      if (error) {
        reject(error);
      }

      resolve({
        edges: doc,
        pageInfo: {
          hasNextPage: '...',
          hasPreviousPage: '...',
          currentPage: '...',
          totalPages: '...'
        }
      });
    }))

知道如何有效地做到这一点吗?

【问题讨论】:

    标签: mongodb mongoose graphql


    【解决方案1】:

    你可以试试这个模块mongoose-paginate

    这里是我使用的,用于分页,

    var current = req.query.filter.current;
    var limit = req.query.filter.limit;
    console.log('params.query.filter.current',current);
    var skip = Number(limit)*Number(current)-Number(limit);
    console.log('skip::',skip);
        Cours.find({'attributes.version.status': true}).skip(skip).limit(limit).sort({_id:'asc'}).exec(function (err, resulta) {
            if (err) {
                console.log('erreur trouverCours');
                res.json({
                    protecteds: err
                });
            }
            console.log('cours ::', resulta);
            res.json({
                "data": resulta
            });
        });
    

    【讨论】:

    • 你试过这个link
    • 谢谢。终于用那个插件解决了。
    • 不客气,如果我的答案是正确的,请将此帖子标记为已解决
    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2014-08-17
    • 1970-01-01
    • 2012-03-08
    • 2020-06-23
    相关资源
    最近更新 更多