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

109
Vistas
find database user by any field passed in params

I am trying to find users in database based on any of three fields. in postman I have the following paths

http://localhost:8082/api/users/617473029f80eda3643a7fdd

http://localhost:8082/api/users/Michael

http://localhost:8082/api/users/25

currently in my database I have all those values for different users. So the idea is that path1 returns the user with that id, path2 returns the user with that name, and path3 user with that age. fyi: I am testing this out so as of now those field values are unique and there are no repeats in database fields.

with the following code, the only thing that returns is when I pass in the id, but the entire database returns. Nothing returns when I pass in name or age

router.get('/:id', (req, res) => {
  User.find( { $or: [
    {"_id": req.params.id},
    {"name": req.params.name},
    {"age": req.params.age}
    ]})
  .then(user => res.json(user))
  .catch(err => res.status(404).json({nouserfound: '***NoUserFound***'}))
});

Thanks!

EDIT: The following worked for me

router.get('/:id', (req, res) => {

  User.find({$or: [
    {name: req.params.id},
    {age: req.params.id}
  ]})
  .then(user => res.json(user))
  .catch(err => res.status(404).json({nouserfound: '*** No User Found ***'}));
  
});

Only problem is that it does not catch the error, so while testing in postman anything that I send in that isn't a match just returns an empty array instead of the err. Not sure how this will affect the program itself or if it's ok

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

req.params.name or req.params.age will be undefined because the route parameter is req.params.id. To get it working correctly, you'll have to look for the value by this route parameter only. The field names change, but the value - req.params.id remains same.

User.find( { $or: [
    {"_id": req.params.id},
    {"name": req.params.id},
    {"age": req.params.id}
    ]})
.then(user => res.json(user))
.catch(err => res.status(404).json({nouserfound: '***NoUserFound***'}))

Optionally: For future usage, rename id to slug would be a better option as this goes well with all other fields on your schema.

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is how mongodb returns the results when you pass undefined/null which it treats as find({}).

You need to make a check if name/age exists. I am pretty sure this route won't use name/age, but uses _id only, so why don't you only pass _id;

router.get('/:id', (req, res) => {

  // check what is available in req.params - name/age/id 
  // based on it create query and run it
  User.find({"_id": req.params.id})
  .then(user => res.json(user))
  .catch(err => res.status(404).json({nouserfound: '***NoUserFound***'}))
});

You should check this link.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You cannot set a different names for each request param, so the req.params.id must be just an id, and won't be available via the name req.params.name

Try to send the request filed via query params, might make it easier. I'd keep the :id endpoint, just a common way to request one user by id, and create another endpoint for all the other requests.

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