简体   繁体   中英

mongodb add item in array

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

在此处输入图像描述 My goal is to add elements to the array of items in the cart.

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,
        }
    }
}
            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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM