简体   繁体   中英

Update shopping cart object inside Meteor user profile

I'm trying to delete from shopping cart, and change quantity information in user profile: here is the structure:

    {
      "_id": "3YmDfDWMAaoeQHPAJ",
      "profile": {
        "name": "Armin",
        "wish": [
          "FMXRAn3TEXCn6skSX",
          "avRwogpGvJsKLLKfK",
          "PJbRh68pwJrtnKe5c",
          "mt2yqLecyTA2Ejd4n"
        ],
        "cart": {
          "mt2yqLecyTA2Ejd4n": "1",
          "xqwfyqasfcyTA2ajd": "3",
          "xL438DBQrNJTJbPmH": "5"
        }
      },
      "username": "armin"
    }

I tried the following but it will delete the whole cart

    let item = $(event.target).data('id');
    Meteor.users.update(Meteor.userId(),{$unset: {"profile.cart": item}});

My goal is to be able to update the value 1,3,5 . and also be able to delete a whole property from cart.

To update an attribute's value in the cart, use $set operator like in the following query:

Meteor.users.update(
    Meteor.userId(),
    {$set: {"profile.cart.xL438DBQrNJTJbPmH": "10"}}
);

To delete an attribute in the cart:

Meteor.users.update(
    Meteor.userId(), 
    {$unset: {"profile.cart.xL438DBQrNJTJbPmH": ""}}
);

The specified value in the $unset expression (ie "") does not impact the operation.

In the case when you have to construct the attribute's name dynamically, you can use an additional variable:

var condition = {}; 
condition["profile.cart." + dynamicPart] = "";
Meteor.users.update(
    Meteor.userId(), 
    {$unset: condition}
);

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