0

I am following a tutorial. I matched everything with the tutorial but my code is not working. It is giving undefined output. I couldn't find where is the mistake and why is it happening?

app.get("/appointment", async (req,res)=>{
      const patient = req.query.patient;
      console.log(patient);
      const query = { patient: patient };
      // console.log(query)
      const appointments = await appointmentCollection.find(query).toArray();
      res.send(appointments)
    }) 

console.log(patient); giving undefined. and res.send(appointments) give an empty array. Please help.

  • 1
    Can you add to the questions how you send the data to the endpoint? – NeNaD Jun 20 '22 at 02:07
  • Actually, I am trying to access data from MongoDB with a specific query using the above code. And when I hit the API console.log(patient); the results are undefined and API returns an empty array on the browser. Please see screenshots in the links https://prnt.sc/cHilL7YNLgKJ , https://prnt.sc/EBQs-hPJ7Lns – Md. Abu Bakkar Siddiq Jun 20 '22 at 02:18
  • You are not passing anything as query params in the image. You are just calling endpoint without passing query params. Check this answer to see how to pass query params in the url: https://stackoverflow.com/a/14508182/14389830 – NeNaD Jun 20 '22 at 02:28
  • You can see a simple example here : https://hoanguyenit.com/create-login-and-register-using-laravel-8-with-react.html – skipperhoa Jun 20 '22 at 02:34
  • In react, you can add data to FormData or json, Nodejs using bodyparser : https://www.npmjs.com/package/body-parser – skipperhoa Jun 20 '22 at 02:36
  • When I pass query then it returns values https://prnt.sc/mMzbJFJvwbup When I am trying to access it from the client end it returns nothing https://prnt.sc/BZ_g_XRhMju_ My client end code https://prnt.sc/BtO098eTxMig – Md. Abu Bakkar Siddiq Jun 20 '22 at 02:48

1 Answers1

0

In your screenshots, you access it as localhost:5000/appointments. req.query.patient looks for ?patient=yourvaluehere after your endpoint, being for example,

localhost:5000/appointments?patient=value

This should now work as a request query. If res.send() sends nothing back, but console.log(patient) does, check your find() function.

more info on req.query - https://www.geeksforgeeks.org/express-js-req-query-property/

async
  • 162
  • 8