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

السؤال

Recommended Posts

  • 0
نشر

ترتيب المسارات لديك في ملف routes\book.routes.ts سبب المشكلة، حيث يتم مطابقة المسارات من أعلى لأسفل عند إرسال طلب، بالتالي إرسال طلب GET إلى /api/book/cart، فيتم مطابقته مع أول مسار وهو bookRouter.get('/:id', getBookById) والذي يعتبر السلسلة النصية cart كقيمة للمُعرف id.

لذا قم بنقل المسار  التالي من السطر 36 إلى 30 قبل bookRouter.get('/:id', getBookById);

bookRouter.get('/cart', isAuthenticate, getCartUser);

 

  • 0
نشر

السلام عليكم ورحمة الله تعالى وبركاته،

هل لا تزال المشكلة قائمة إلى الآن؟ في حال كانت كذلك أرجو الاطلاع على هاته الإجابة.

المشكلة في الخطأ الذي ظهر لك:

Cast to ObjectId failed for value 'cart' (type string) at path '_id' for model 'Book

سببها أن لديك في ال Router endpoint /cart و /cart/:id وعند استدعاء GET /api/book/cart يمرر اسم "cart" كمعرّف بدل ObjectId في استعلام الكتاب وذلك بسبب ترتيب تعريف الروتس في الكود ففي الترتيب الحالي:

bookRouter.get('/:id', getBookById);
bookRouter.get('/cart', isAuthenticate, getCartUser);

إذا جاء الطلب ل /cart بدون معرّف هنا Express يطابقه أولا مع /api/book/:id ويعتبر "cart" هو المعرف ويدخله ك param في getBookById، وبالتالي يبحث في قاعدة البيانات عن كتاب معرفه "cart" فيفشل ال cast إلى ObjectId لحل المشكلة يجب تغيير ترتيب تعريف الروتس بحيث تكون المسارات الثابتة مثل /cart قبل المتغيرة مثل /:id هكذا:

bookRouter.get('/cart', isAuthenticate, getCartUser); 
bookRouter.get('/:id', getBookById); 

لتكون في النهاية هكذا:

bookRouter.get('/', getAllBooks);
bookRouter.get('/cart', isAuthenticate, getCartUser);
bookRouter.post('/cart/:id', isAuthenticate, addToCart);
bookRouter.delete('/cart/:id', isAuthenticate, deleteBookCart);
bookRouter.get('/favorite', isAuthenticate, getFavoriteUser);
bookRouter.post('/favorite/:id', isAuthenticate, addToFavorite);
bookRouter.delete('/favorite/:id', isAuthenticate, deleteFavorite);
bookRouter.get('/user', isAuthenticate, getBooksUser);
bookRouter.put('/:id', isAuthenticate, updateBook);
bookRouter.delete('/:id', isAuthenticate, deleteBook);
bookRouter.get('/:id', getBookById);
bookRouter.post('/upload', isAuthenticate, upload.single("image"), uploadBook);
bookRouter.post('/profile', isAuthenticate, profileUser);

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

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

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

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   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.

  • إعلانات

  • تابعنا على



×
×
  • أضف...