NMTEG
@NMTEG
Почти junior :)

Почему из MongoDB получаю данные, которые на одно действие отстают?

Т.е. я делаю определенный запрос, совершаю какое-то действие, данные в самой коллекции обновляются, а вот в res() он отправляют то, что было до этого действия.

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 })}};
  • Вопрос задан
  • 92 просмотра
Решения вопроса 1
@Corvuss
https://www.mongodb.com/docs/manual/reference/meth...

Returns the original document by default. Returns the updated document if returnNewDocument is set to true or returnDocument is set to after.

Нужно флаг передать в параметрах, чтобы вернул обновленный документ.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы