I have not found how to return total data included in the resultset. Is there any way to return total data? I need to confirm that the correct JSON data is returned.
What I want is to have something like this returned:
total: 40,
page: 1,
pageSize: 3,
books: [
{
_id: 1,
title: "达·芬奇密码 ",
author: "[美] 丹·布朗",
},
{
_id: 2,
title: "梦里花落知多少",
author: "郭敬明",
},
{
_id: 3,
title: "红楼梦",
author: "[清] 曹雪芹",
}
]
}
Current code:
router.get('/booksquery', (req, res) => {
var page = parseInt(req.query.page) || 1;
var limit = parseInt(req.query.limit) || 3;
Book.find({})
.sort({ update_at: -1 })
.skip((page-1) * limit)
.limit(limit)
.exec((err, doc) => {
if (err) {
res.json(err)
} else {
res.json({
total: doc.total,
page: page,
pageSize: limit,
books:doc,
});
}
})
})
0
default and pagination starts with next page, that is1
, your could do.skip(page * limit)
make sure.skip()
and.limit()
gets Number.