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?