Reputation: 53
I'm quite new to Node.js and I'm trying to build a pagination feature for my "Get all users" page in async/await. But I seem to have bumped into a hurdle and after an extensive research (both here, other sources and even tutorials), I still can't come up with a solution. All the solutions I've seen show me how to do either. This is the code:
mongoOp.countDocuments({},function(err,totalCount) {
if(err) {
response = {"error" : true,"message" : "Error fetching data"}
}
mongoOp.find({},{},query,function(err,data) {
// Mongo command to fetch all data from collection.
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
var totalPages = Math.ceil(totalCount / size)
response = {"error" : false,"message" : data,"pages": totalPages};
}
res.json(response);
});
});
I have figured out how to write both countDocuments() and find() functions in async/await to produce results as the following send correct json responses:
The countDocuments() function
try {
totalDocs = await mongoOp.countDocuments();
return res.status(200).json({totalDocs})
} catch (err) {
return res.send(err)
}
};
The find() query:
try {
const users = await mongoOp.find({}, {}, query);
return res.status(200).json({
status: users
});
} catch (error) {
return res.status(400).send(error);
}
However, I don't know how to put them together to produce the needed results. I would be very grateful if I could be assisted.
Upvotes: 0
Views: 43
Reputation: 664195
You seem to be looking for
try {
const totalCount = await mongoOp.countDocuments();
const totalPages = Math.ceil(totalCount / size)
const data = await mongoOp.find({}, {}, query);
return res.status(200).json({"error":false, "message":data, "pages":totalPages});
} catch (err) {
return res.status(500).json({"error":true, "message":"Error fetching data"});
}
Upvotes: 1