The code below is working, however, I think it is a lot of coding. I am uncomfortable with this. Does someone know a more concise way to write this?
The main goal is extracting a sort param from a HTTP query and sort a Mongoose/Mongodb collection.
The sort query is GET /flavors?sort=id ASC, so, I took this string ["id", "ASC"] in sort and transformed it in {id : ASC} in sortStr
router.get("/", (req, res) => {
var { sort } = req.query;
var v_fields = sort.split(",");
var v_field = v_fields[0].replace('[', '');
var v_order = v_fields[1].replace(']', '');
var sortStr = `{ ${v_field} : ${v_order} }`;
var re = new RegExp(`"`, 'g');
sortStr = sortStr.replace(re, '');
Flavor.find().sort(sortStr).then(result => {
...
}
?sort=id&sort=ASCI believe thatreq.query.sortwould be['id', 'ASC']using body parser with a particular configuration. Might have to dig around, but that would probably be more robust than doing hand-written string manipulation to get the format you want./flavors?sort[id]=ASCand accessed viareq.query.sort=>{id: 'ASC'}.