skip to Main Content

Everything works fine, but the data I get in res() is one step behind. I rewrote the entire code a hundred times and no longer understand what the problem is

here is part of the code backend on express.js, node.js and mongodb:

export const addToCart = async (req, res) => { try {
const cart = await CartModul.findOne({ user: req.userId });
if (cart) {
  const product_id = req.body.product_id;
  const item = cart.cartItems.find((c) => c.product_id == product_id);
  console.log("item", item);
  if (item) {
    try {
      const cart = await CartModul.findOneAndUpdate(
        { user: req.userId, "cartItems.product_id": product_id },
        {
          "cartItems.$": {
            ...req.body,
            quantity: item.quantity + req.body.quantity,
            totalPrice: item.totalPrice + req.body.price,
          },
        }
      );
      if (cart) {
        return res.status(200).json({ cart });
      }
    } catch (error) {
      return res.status(400).json({ error });
    }
  } else {
    try {
      const cart = await CartModul.findOneAndUpdate(
        { user: req.userId },
        {
          $push: {
            cartItems: req.body,
          },
        }
      );
      if (cart) {
        return res.status(200).json({ cart });
      }
    } catch (error) {
      return res.status(400).json({ error });
    }
  }
} else {
  try {
    const cart = new CartModul({
      user: req.userId,
      cartItems: req.body,
    });
    cart.save();
    res.json(cart);
  } catch (error) {
    return res.status(400).json({ error });
  }
} } catch (error) {
return res.status(400).json({ error })}};

2

Answers


  1. Chosen as BEST ANSWER

    Use {new: true) in findOneAndUpdate() and make async in moment with save()


  2. In the else condition add await. i.e.

    let newCart = await cart.save();
    res.json(newCart);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search