Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda