I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example:
http://localhost:3000/patient?filter=name:jack
I have implemented a method to retrieve and convert these URL parameters into a JSON object:
const filter = handleQueryFilter(req.query.filter)
const handleQueryFilter = (query) => {
try{
// Convert the string to resemble a JSON object
// For example, id: -1, name: 1 becomes { 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 an empty JSON object if the client inputs the wrong query format
}
}
The result returned from the 'handleQueryFilter' function is then passed to the 'find' method to retrieve data from the database.
let patients = await Patient.find(filter);
However, I'm facing an issue where the 'handleQueryFilter' function always returns an empty object (as indicated in the catch block above). Can anyone point out what might be going wrong?