Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda