Home > Software engineering >  Array Find() method is always returning 'undefined' while searching data with respect to U
Array Find() method is always returning 'undefined' while searching data with respect to U

Time:12-09

I want to show the data from the array of whole data which should satisfy the condition that the requested id matches with the id of the data. But every time I try the below code, I only get 'undefined' as an output from the find method.

Code


    import express from 'express';
    import data from "./data.js"
    
    const app=express(); 
    app.get('/products/api/:id',(req,res)=>{
        const product = data.products.find((x) => x.id === req.params.id);
          if (product) {
               res.send(product)
          }
          else{
              res.status(404).send({message:`Product Not Found${req.params.id}`});
          }
      }) app.get('/products/api',(req,res)=>{
        res.send(data.products) 
      }) app.get('/',function(req,res){
        res.send("server is ready") 
      }) const port=process.env.PORT || 5000 app.listen(5000,()=>{
        console.log(`serve at http://localhost:${port}`);
     })

CodePudding user response:

Your code is missing body parsing middleware. Try adding an

app.use(express.json({ extended: true })) before your routes.

Also please check if the id from data.products.find((x) => x.id === req.params.id); is of type string. It might be a number or an ObjectId mongoose object id.

CodePudding user response:

All you need to do is,

change this:

const product = data.products.find((x) => x.id === req.params.id);

to:

const product = data.products.find((x) => x.id == req.params.id);
  • Related