Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
query parameter not in the correct syntax

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!