Skip to content

Instantly share code, notes, and snippets.

@jasjar
Last active January 19, 2023 20:13
Show Gist options
  • Save jasjar/47d35b9b417bc15d911f30daf1d8018e to your computer and use it in GitHub Desktop.
Save jasjar/47d35b9b417bc15d911f30daf1d8018e to your computer and use it in GitHub Desktop.
Mongoose query - use limit, sort, fields, paging options
const getStories = (category, fields, sort, limit, page, callback) => {
//default values for these should be moved to config module
const f = (fields && fields !== 'all') ? fields.replace(new RegExp(',', 'g'), ' ') : (fields !== 'all') ? 'id category headline teaser author create_date' : null;
const s = (sort) ? sort.replace(new RegExp(',', 'g'), ' ') : '-create_date';
const l = (limit) ? Number(limit) : 10;
const p = (page) ? Number(page) : 0;
//Story here is a previously create Mongoose model
let query = Story.find({ category: category });
//Set options
if (f) query.select(f);
if (s) query.sort(s);
query.limit(l);
query.skip(l * p);
//Execute
query.exec((err, stories) => {
if (err) return callback(err);
callback(null, stories);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment