1
            await Cart.update(
              { $elemMatch: { user_id: decoded._id } },
              {
                $addToSet: {
                  "cart.&.items": {
                    product_id: req.query.product_id,
                    quantity: 1,
                  },
                },
              }
            );

enter image description here My goal is to add elements to the array of items in the cart.

1
  • 2
    Please edit your question by replacing the screenshot with text (copy & paste). Not only do links die, but it poses problems for the visually impaired. Commented Apr 8, 2020 at 15:02

2 Answers 2

1

There's no syntax with & sign. MongoDB offers $ as a positional operator which allows you to modify existing item but you don't needed since you just want to append a new object to an array, try:

{
    $addToSet: {
        "cart.items": {
            product_id: req.query.product_id,
            quantity: 1,
        }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Do I need to use the elemMatch structure? @mickl
@Anonim just use { user_id: decoded._id }, $elemMatch is for querying the array
It finds but did not add. Why not add :(
@Anonim so you were using $addToSet but same value was already there?
|
0
            Cart.updateMany(
              { user_id: decoded._id },
              {
                $push: {
                  "cart.items": {
                    product_id: req.query.product_id,
                    quantity: 1,
                  },
                },
              }
            )

I finally found the right method through trial and error.

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.