Search code examples
node.jsmongodbexpressmern

data is showing undefine how would it could correct


This is error:

D:\LCO bootcamp\Project_Backend\controllers\product.js:50 product.photo.data = fs.readFileSync(file.photo.path); ^

TypeError: Cannot set properties of undefined (setting 'data')

Code:

if (file.photo) {
      if (file.photo.size > 3000000) {
        return res.status(400).json({
          error: "File size too big!"
        });
    }

      
      product.photo.data = fs.readFileSync(file.photo.filepath);
      product.photo.contentType = file.photo.mimetype;
}

'


Solution

  • Move product.photo.data = fs.readFileSync(file.photo.filepath) and product.photo.contentType = file.photo.mimetype to inside if(product.photo){...} :

    if (file.photo) {
              if (file.photo.size > 3000000) {
                return res.status(400).json({
                  error: "File size too big!"
                });
            }
        
              if(product.photo){
                product.photo.data = fs.readFileSync(file.photo.filepath);
                product.photo.contentType = file.photo.mimetype;
              }
              
        }