Strapi Not able to save cart collections and not event showing detailing error

Strapi Not able to save cart collections and not event showing detailing error
src/api/cart/controllers/cart.js

"use strict";

/**
 * cart controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController("api::cart.cart", ({ strapi }) => ({
  async createCartData(ctx) {
    try {
      function isCartIdOnlyNumbers(cartId) {
        return /^[0-9]+$/.test(cartId);
      }

      const { id } = ctx.params; // guest_id or numeric user id
      const { user, items = [] } = ctx.request.body;
      const userId = user?.id;

      let cart = null;

      // 🧠 Helper to calculate totals
      const processProducts = (items) => {
        return items.map((item) => {
          const total = item.extra_info.reduce((sum, ei) => sum + ei.price, 0);
          const line_price = total * item.quantity;

          return {
            __component: "shared.product-detail",
            product:
              typeof item.product === "object" && item?.product?.id
                ? Number(item.product.id)
                : Number(item.product),
            quantity: Number(item.quantity),
            total: Number(total),
            line_price: Number(line_price),
            extra_info: item.extra_info.map((ei) => ({
              __component: "shared.extra-info",
              license:
                typeof ei.license === "object" && ei?.license?.id
                  ? Number(ei.license.id)
                  : Number(ei.license),

              price: Number(ei.price),
            })),
          };
        });
      };

      const formattedProducts = processProducts(items);
      const totalCartPrice = formattedProducts.reduce(
        (sum, p) => sum + p.line_price,
        0
      );

      if (!isCartIdOnlyNumbers(id)) {
        // id is guest_id
        cart = await strapi.db.query("api::cart.cart").findOne({
          where: { guest_id: id },
        });

        if (cart) {
          if (userId) {
            // Update guest cart to assign user and null guest_id
            cart = await strapi.db.query("api::cart.cart").update({
              where: { id: cart.id },
              data: {
                user: userId,
                guest_id: null,
                products: formattedProducts,
                totalPrice: totalCartPrice,
              },
            });
          } else {
            // Just update products in guest cart
            cart = await strapi.db.query("api::cart.cart").update({
              where: { id: cart.id },
              data: {
                products: formattedProducts,
                totalPrice: totalCartPrice,
              },
            });
          }

          return ctx.send({
            result: true,
            message: "Cart updated successfully",
            data: cart,
          });
        }

        // No guest cart found
        if (userId) {
          const existingUserCart = await strapi.db
            .query("api::cart.cart")
            .findOne({
              where: { user: userId },
            });

          if (existingUserCart) {
            // Update user cart with guest_id + new products
            cart = await strapi.db.query("api::cart.cart").update({
              where: { id: existingUserCart.id },
              data: {
                guest_id: id,
                products: formattedProducts,
                totalPrice: totalCartPrice,
              },
            });
          } else {
            // Create new cart
            cart = await strapi.db.query("api::cart.cart").create({
              data: {
                guest_id: id,
                user: userId,
                products: formattedProducts,
                totalPrice: totalCartPrice,
              },
            });
          }

          return ctx.send({
            result: true,
            message: "Cart created or updated with guest ID and user",
            data: cart,
          });
        }

        // Guest-only cart
        cart = await strapi.db.query("api::cart.cart").create({
          data: {
            guest_id: id,
            products: formattedProducts,
            totalPrice: totalCartPrice,
          },
        });

        return ctx.send({
          result: true,
          message: "Guest cart created",
          data: cart,
        });
      } else {
        // id is a numeric user ID
        const existingUserCart = await strapi.db
          .query("api::cart.cart")
          .findOne({
            where: { user: id },
          });

        if (existingUserCart) {
          // Update existing cart

          cart = await strapi.db.query("api::cart.cart").update({
            where: { id: existingUserCart.id },
            data: {
              user: parseInt(id),
              guest_id: null,
              products: formattedProducts,
              totalPrice: totalCartPrice,
            },
          });

        } else {
          // Create new cart
          cart = await strapi.db.query("api::cart.cart").create({
            data: {
              user: parseInt(id),
              guest_id: null,
             products: formattedProducts,
              totalPrice: totalCartPrice,
            },
          });
        }

        return ctx.send({
          result: true,
          message: "User cart created or updated",
          data: cart,
        });
      }
    } catch (error) {
      console.error("Error in createCartData:", error);
      return ctx.throw(500, "Internal server error");
    }
  },
}));


showing error like

Error in createCartData: Error: Invalid id, expected a string or integer, got [object Object] at /var/www/demo.com/node_modules/@strapi/database/dist/index.js:6450:19 at Array.map () at toIdArray (/var/www/demo.com/node_modules/@strapi/database/dist/index.js:6440:70) at toAssocs (/var/www/demo.com/node_modules/@strapi/database/dist/index.js:6459:42) at Object.updateRelations (/var/www/demo.com/node_modules/@strapi/database/dist/index.js:6986:43) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Object.update (/var/www/demo.com/node_modules/@strapi/database/dist/index.js:6681:17) at async Object.createCartData (/var/www/demo.com/src/api/cart/controllers/cart.js:216:16) at async returnBodyMiddleware (/var/www/demo.com/node_modules/@strapi/core/dist/index.js:2485:20) at async policiesMiddleware (/var/www/demo.com/node_modules/@strapi/core/dist/index.js:2443:9) [2025-04-18 06:40:56.832] error: Internal server error InternalServerError: Internal server error at Object.throw (/var/www/demo.com/node_modules/koa/lib/context.js:97:11) at Object.createCartData (/var/www/demo.com/src/api/cart/controllers/cart.js:245:21) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async returnBodyMiddleware (/var/www/demo.com/node_modules/@strapi/core/dist/index.js:2485:20) at async policiesMiddleware (/var/www/demo.com/node_modules/@strapi/core/dist/index.js:2443:9) at async /var/www/demo.com/node_modules/@strapi/core/dist/index.js:2466:20 at async /var/www/demo.com/node_modules/@strapi/core/dist/index.js:4691:17 at async /var/www/demo.com/node_modules/@strapi/core/dist/index.js:4649:9 at async cors (/var/www/demo.com/node_modules/@koa/cors/index.js:106:16) at async /var/www/demo.com/node_modules/@strapi/core/dist/index.js:4580:13 enter code here

Answer

Not getting this question answer i also have same problem

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles