0

I am trying to filter a collection by name (or other fields) by checking the url parms and its value e.g

http://localhost:3000/patient?filter=name:jack

I have a method to retrieve the url pram and convert it to a json object:

const filter = handleQueryFilter(req.query.filter)

const handleQueryFilter = (query) => {
    try{
      // convert the string to look like json object
      // example id: -1, name: 1 to { id: "-1"}, {name: "1" }
      const toJSONString = ("{" + query  ).replace(/(\w*[^:].$)/g, (matched => {
       return '"' + matched.substring(0, matched.length ) + '"}'  ;
    }));
      
      return JSON.parse(toJSONString);
    }catch(err){
      return JSON.parse("{}"); // parse empty json if the clients input wrong query format
    }
  }

What ever returned from the 'handleQueryFilter' is passed to the 'find' method to get the result from the database

let patients = await Patient.find(filter);

However handleQueryFilter always returns an empty object (the catch part above), what am I doing wrong?

Omar
  • 1
  • 1
  • remove the / from the URL before query params `http://localhost:3000/patient?filter=name:jack` – cmgchess Oct 23 '21 at 20:53
  • also `:` is a reserved character at `name:jack` https://stackoverflow.com/questions/2366260/whats-valid-and-whats-not-in-a-uri-query – cmgchess Oct 23 '21 at 21:28

2 Answers2

0

First: make express pasre req.body automatically by using

app.use(express.json())

Edit you URL to be: http://localhost:3000/patient?name=jack

0

Your replace operation does not what it is supposed to do:

"{id: -1, name: 1".replace(/(\w*[^:].$)/g, (matched => {
       return '"' + matched.substring(0, matched.length ) + '"}'
}))

returns '{id: -1, name:" 1"}', which is not valid JSON, therefore JSON.parse gives an error.

Try something like

Object.fromEntries("id: -1, name: 1".split(/,\s*/).map(_=>_.split(/:\s*/)))

which returns {id: '-1', name: '1'} without the need for JSON.parse.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31