search

Home  >  Q&A  >  body text

Rewrite the title as: MongoDB stores key data in collections but sends expired data to res()

Everything runs fine, but the data I get in res() is one step behind the actual operation. I've rewritten the entire code a hundred times and no longer understand what the problem is.

This is part of the backend code, using 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 })}};

P粉585541766P粉585541766301 days ago369

reply all(2)I'll reply

  • P粉674876385

    P粉6748763852024-01-17 22:21:52

    Use {new: true} in findOneAndUpdate(), and use save() in moment for asynchronous operation

    reply
    0
  • P粉574268989

    P粉5742689892024-01-17 11:04:50

    Add await in the else condition. Right now:

    let newCart = await cart.save();
    res.json(newCart);

    reply
    0
  • Cancelreply