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?
CodePudding user response:
First: make express pasre req.body automatically by using
app.use(express.json())
Edit you URL to be:
http://localhost:3000/patient?name=jack
CodePudding user response:
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
.