0

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 => {
...
}
3
  • 1
    If you changed the query to be ?sort=id&sort=ASC I believe that req.query.sort would 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. Commented Sep 14, 2018 at 15:02
  • 2
    Or IF you want to use an object then Express can automatically handle it if you structure the query as such: /flavors?sort[id]=ASC and accessed via req.query.sort => {id: 'ASC'}. Commented Sep 14, 2018 at 15:04
  • @JasonCust very good point Commented Sep 14, 2018 at 15:13

2 Answers 2

1

If I understand you correctly, and your sort string always represents an array containing two elements, you could do something like this:

var s='["id", "ASC"]';
var arr=JSON.parse(s);
var sortObj={};
sortObj[arr[0]]=arr[1];
Sign up to request clarification or add additional context in comments.

1 Comment

That is perfect, it worked and reduced a lot of code. Thanks.
0

Yes there is:

 const [key, order] = req.query.sort.split(" ");
 Flavor.find().sort({ [key]: order }).then(/*...*/);

Concerning your code:

1) vfields is an array, and the arrays elements do not contain any [ or ] in your example so there is no need to remove them.

2) sort expects an object, so you should pass an object not a string.

1 Comment

It does not work, when I extract the sort from the req it is a string representing an array, not an array. So, it has [ and ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.