Search code examples
node.jsmulter

when I try to save without image it shows the following error " "message": "Cannot read property 'path' of undefined".?"


when I try to save without image it shows the following error " "message": "Cannot read property 'path' of undefined".?"

    // product controller
  exports.products_create_product = (req, res, next) => {
  const product = new Product({
  _id: new mongoose.Types.ObjectId(),
  name: req.body.name,
  price: req.body.price,
  productImage: req.file.path
  });
  product
  .save()
  .then(result => {
  console.log(result);
  res.status(201).json({
    message: "Created product successfully",
    createdProduct: {
      name: result.name,
      price: result.price,
      _id: result._id,
      request: {
        type: "GET",
        url: "http://localhost:3000/products/" + result._id
      }
    }
  });
  })
  .catch(err => {
  console.log(err);

  res.status(500).json({

    error: err
  });
  });
  };

// Following is my product routes

  router.post("/", checkAuth, upload.single('productImage'), 
  ProductsController.products_create_product);

Solution

  • Make check like

    req.file? req.file.path : null