Home > Net >  MongoDB saves the necessary data to the collection, but outdated data goes to res()
MongoDB saves the necessary data to the collection, but outdated data goes to res()

Time:02-01

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 })}};

CodePudding user response:

In the else condition add await. i.e.

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

CodePudding user response:

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

  • Related