اذهب إلى المحتوى
  • 0

خطأ عند استخدام Mongoose و Multer لرفع عدة صور على NodeJS

أحمد عبد الله2

السؤال

اريد رفع بضعة صور باستخدام المكتبة multer ولكن يظهر لى هذا الخطأ 

D:\1-Node JS\Projects\E-Commerce\node_modules\mongoose\lib\query.js:4545 const castError = new CastError(); ^ CastError: Cast to ObjectId failed for value "gallery-images" (type string) at path "_id" for model "User"


هذا هو كودى 

const express = require("express");
const { ProductModel } = require("../model/product");
const multer = require("multer");

const router = express.Router();

const FILE_TYPE_MAP = {
  "image/png": "png",
  "image/jpeg": "jpeg",
  "image/jpg": "jpg",
};

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const isValid = FILE_TYPE_MAP[file.mimetype];
    let uploadError = new Error("invalid image type");

    if (isValid) {
      uploadError = null;
    }
    cb(uploadError, "public/uploads");
  },
  filename: function (req, file, cb) {
    const fileName = file.originalname.split(" ").join("-");
    const extension = FILE_TYPE_MAP[file.mimetype];
    cb(null, `${fileName}-${Date.now()}.${extension}`);
  },
});

const uploadOptions = multer({ storage: storage });

router.put(
  "/gallery-images/:id",
  uploadOptions.array("images", 10),
  async (req, res) => {
    const files = req.files;
    let imagesPaths = [];
    const basePath = `${req.protocol}://${req.get("host")}/public/uploads/`;

    if (files) {
      files.map((file) => {
        imagesPaths.push(`${basePath}${file.filename}`);
      });
    }

    const product = await ProductModel.findByIdAndUpdate(
      req.params.id,
      {
        images: imagesPaths,
      },
      { new: true }
    );

    if (!product) return res.status(500).send("the gallery cannot be updated!");

    res.send(product);
  }
);

module.exports = router;

 

تم التعديل في بواسطة Hassan Hedr
توضيح السؤال
رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

للعثور على الحل في الغالب انت فقط تحتاج لبعض ال console.logs

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const isValid = FILE_TYPE_MAP[file.mimetype];
    let uploadError = new Error("invalid image type");

    if (isValid) {
      uploadError = null;
    }
    cb(uploadError, "public/uploads");
  },
  filename: function (req, file, cb) {
    const fileName = file.originalname.split(" ").join("-");
    
    console.log(filename) // تحقق هنا
    
    const extension = FILE_TYPE_MAP[file.mimetype];
    cb(null, `${fileName}-${Date.now()}.${extension}`);
  },
});

وأيضا

router.put(
  "/gallery-images/:id",
  uploadOptions.array("images", 10), // الاسم هنا مهم ويجب أن يستعمل في الواجهة 
  async (req, res) => {
    const files = req.files;
    let imagesPaths = [];
    const basePath = `${req.protocol}://${req.get("host")}/public/uploads/`;
    
    console.log("basePath",basePath)// تحقق هنا
    

    if (files) {
      files.map((file) => {
        imagesPaths.push(`${basePath}${file.filename}`);
      });
    }
    
        console.log("imagesPaths",imagesPaths)// تحقق هنا
    
        console.log("req.params.id",req.params.id)// تحقق هنا
    


    
    const product = await ProductModel.findByIdAndUpdate(
      req.params.id,
      {
        images: imagesPaths,
      },
      { new: true }
    );

    if (!product) return res.status(500).send("the gallery cannot be updated!");

    res.send(product);
  }
);

تحقق أيضا من ال model الخاص بك ProductModel

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 0

لديك خطأ في مكان آخر يتعلق بالبحث عن المستخدم باستخدام المعرّف الخاص به من خلال User Model،

تحقق من أن القيمة الممررة كمعرف للبحث عن المستخدم، يمكنك تحويل القيمة الممررة كمعرف باستخدام التابع fromString قبل تمريره للبحث كالتالي:

ObjectId.fromString( /* المعرف هنا */ );

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...