How to implement pagination for mongodb in node.js using official mongodb client?

前端 未结 4 1407
無奈伤痛
無奈伤痛 2021-01-16 02:34

I want to implement pagination for mongodb in node.js enviroment using offical mongodb package. I tried to find out on internet but all are mongoose based links. I dont want

4条回答
  •  隐瞒了意图╮
    2021-01-16 03:15

    I am sending an API that is on MongoDb and Nodejs.

    module.exports.fetchLoans = function(req, res, next) {
        var perPage = 5;
        var page = req.body.page || 1;
        loans
          .find({ userId: req.user._id})
          .select("-emi")
          .skip(perPage * page - perPage)
          .limit(perPage)
          .sort({ timestamp: -1 })
          .exec(function(err, loan) {
            if (loan != null) {
              loans
                .find({ userId: req.user._id})
                .count()
                .exec(function(err, count) {
                  if (count != null) {
                    res.json({
                      success: true,
                      loans: loan,
                      currentpage: page,
                      totalpages: Math.ceil(count / perPage)
                    });
                  } else {
                    console.log("Milestone Error: ", err);
                    res.json({ success: false, error: "Internal Server Error. Please try again." });
                  }
                });
            } else {
              console.log("Milestone Error: ", err);
              res.json({ success: false, error: "Internal Server Error. Please try again." });
            }
          });
      };
    

    In this code, you will have to provide page number on every hit.

提交回复
热议问题