NodeJs mongodb query to fetch collection data with total length offset and limit

This is how we query from mongodb collection to fetch data with total length, offset and limit. For total length we need to use async.

let url = "mongodb+srv://";

	mongoose.set("useNewUrlParser", true);
	mongoose.set("useUnifiedTopology", true);
	mongoose.connect( url, (err, database) => { 
		if(err) {
			return console.error(err);
		db = database;


exports.getAllMinisters = async (req, res, next)=>{
	totalCount  = await db.collection('allMinisters').countDocuments({});
	db.collection('allMinisters').find({}).skip(0).limit(10).toArray(function (err, docs) {
		if (err) {return next(err);}
			const response = {
				totalCount: totalCount,
				length: docs.length,
				status: 'success'
		res.statusCode = 200;
		res.setHeader('Content-Type', 'application/json');

Leave a Reply

Your email address will not be published. Required fields are marked *