Harish
Harish

Reputation: 123

Cannot read property 'metadata' of null Nodejs

This is my error:

 TypeError: Cannot read property 'metadata' of null
 at gfs.files.findOne (M:\FinalProject\Commerce\routes\index.js:187:13)
 at result (M:\FinalProject\Commerce\node_modules\mongodb\lib\utils.js:414:17)

This is my code :

    router.get('/:filename', (req,res) => {
    const img = req.params.filename; // Filename
     gfs.files.findOne({filename: img}, (req,file) =>{


  if(file.metadata.brand=="Mango"){
  const brand = "Mango";
   displayOne(brand);
  }
  else if(file.metadata.brand=="Cocotail")
  {
  const brand = "Cocotail";
   displayOne(brand);
  }
  else if(file.metadata.brand==null)
  {  
   console.log("Null");

   }




   function displayOne(brand)
    {
   gfs.files.find({'metadata.brand': brand }).toArray((err,files)=>{

   if(!file || file.length ===0)
   {
   return res.status(404).json({
    err: 'No files exist'
   });
  }

   if(file.contentType === 'image/jpeg' || file.contentType === 'image/png')
  {

   file.isImage = true;
   }
   else
  {
  res.status(404).json({
    err: 'Not an image'
  });
  file.isImage = false;
  }


   res.render('singleproduct',{
    file:file,
    relatedProduct:files, // Related Products
    isSearch:0

  });
  });

  }

 });
 });

Please give me any ideas about this error. i couldn't find out what is the major reason for this error. I searched on google but there are no appropriate solutions for that.____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Thank you

Upvotes: 0

Views: 2385

Answers (1)

Shivani Tyagi
Shivani Tyagi

Reputation: 182

Did you console what you get just above

(file.metadata.brand=="Mango")

in file? seems you don't get any data from

gfs.files.findOne({filename: img}

try this:

 if(file && file.metadata.brand=="Mango"){
  const brand = "Mango";
   displayOne(brand);
  }
  else if(file && file.metadata.brand=="Cocotail")
  {
  const brand = "Cocotail";
   displayOne(brand);
  }
  else if(file && file.metadata.brand==null)
  {  
   console.log("Null");

   }
else{
    console.log("didinot find value")
}

Upvotes: 1

Related Questions