Javascript - Compare input field to mongodb field

Asked

Viewed 72 times

0

Can anyone give me information about this? I’m trying to learn or else demonstration with explanation

What I want to do is to have html input and fetch the value of this input check if it exists in a certain collection and if it exists does something if it does not do something!

Thanks to those who help!

I’m a beginner in the field

1 answer

1

Assuming you’re using Mongoose and Express, in your controller you can do:

function findOneInput(req, res) {
   Model.findOne({ field: req.query.input }, function (error, input) {
      // Trata erro
      if(error) {
         console.error(error)
         res.status(500).msg({ msg: 'Um erro ocorreu' })
      }
      // Manda o documento para o usuario
      res.json(input)     
   })
}

Already in the view, you would need to make a request to your API, passing the input to the query. URI would be: example.com/api/nome-da-rota?input=valor-do-usuario. The API would return you null if the document does not exist in DB and returns the document if it exists. Then just do an if.

P.S.: That’s pretty general, it’s an assumption according to what you published. It may be that other adjustments have to be made regarding security, performance and even how you set your data.

  • Friend I think I will need a more detailed explanation what I want is to compare what the user insert in an input and I want to check if it exists in the database Do you understand? I think I explained myself as soon as I’ll rephrase in the post

  • That’s exactly what the code is doing. You receive this information from the user in an HTML file, and make a request in your API to check if there is a field with this data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.