Last active
January 19, 2023 20:13
-
-
Save jasjar/47d35b9b417bc15d911f30daf1d8018e to your computer and use it in GitHub Desktop.
Mongoose query - use limit, sort, fields, paging options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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