1

Building cart on website and when product is added i want to first check if it is already in cart, if yes increment quantity by 1, if not add it. Cart is an array of objects and i want to pass index of object that contains added product to increment function but can't figure out how to do so.

async function add(product, userId) {
      const user = await User.findById(userId);
      const product = isProductInCart(product, user.cart); // returns true and index in cart if found
      if (product.found === true) {
        await User.findOneAndUpdate(
          { _id: userId },
          { $inc: { cart[product.index].quantity : 1 }} // not working
        );
      } else {
        await User.findOneAndUpdate({ _id: userId }, { $push: { cart: product } });
      }
    }

function isProductInCart(product, cart) {
  let productFound = { found: false, index: -1 };
  for (let i = 0; i < cart.length; i++)
    if (cart[i].name === product.name) {
      productFound.found = true;
      productFound.index = i;
      break;
    }
  return productFound;
}
1
  • Can you show the isProductInCart function? Commented Jul 16, 2020 at 13:34

1 Answer 1

1

It looks like your code can be simplified if you consider using the $ positional operator:

let userWithCart = User.findOneAndUpdate(
    { _id: user, 'cart.name': product.name },
    { $inc: { 'cart.$.quantity' : 1 }}
)

if(!userWithCart ){
    await User.findOneAndUpdate({ _id: userId }, { $push: { cart: product } });
}

First findOneAndUpdate will return no value when there's no corresponding cart.name (and you need to $push it). Otherwise MongoDB will automatically match the cart you want to update based on cart.name condition and increment the quantity subfield.

EDIT: If you still need to proceed the way you've started you just need to evaluate the path in JavaScript:

{ $inc: { [`cart.${product.index}.quantity`] : 1 }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.