Just another WordPress site

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://demodbuser:demodbpassword@myuser.zfebp.mongodb.net/demodb?retryWrites=true&w=majority";

	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,
				allMinisters: docs.map(docs=>docs),
				status: 'success'
			}
		res.statusCode = 200;
		res.setHeader('Content-Type', 'application/json');
		res.end(JSON.stringify(response));
	});
};

Leave a Reply

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