0

Suppose you have a collection called bar in a MongoDB, which has the following items :

"items" : [
    {
        "item_name" : "my_item_one",
        "price" : 20
    },
    {
        "item_name" : "my_item_two",
        "price" : 50
    },
    {
        "item_name" : "my_item_three",
        "price" : 30
    }
]

How can i add a new field called discount to each entry in the items array? I tried this without luck :

var dynamicItem = "items.$.discount"
    Bar.update( {user_id : 123456} , {$set : {dynamicItem : 5} })
mixel
  • 25,177
  • 13
  • 126
  • 165
yusha uzumo
  • 211
  • 1
  • 4
  • 15
  • @mixel. thanks for editing my question If there is anyone out there with insights on how to achieve the above your help will be appreciated. Note that the part that is answered has been deleted and only the part without an answer is left. – yusha uzumo Jul 11 '15 at 18:40
  • do not delete the answered part. Some people might be looking out for an answer to same question! – goku Apr 19 '16 at 07:22

1 Answers1

1

the first one is not possible at the moment, see this answer.

for the second one, try this:

var dynamicItem = {};
dynamicItem["itemsCollectionName"] = "Beer pack";

Bar.update( {user_id : 123456} , {$set : dynamicItem })
Community
  • 1
  • 1
tomsp
  • 1,797
  • 14
  • 17
  • Sweet, thanks. I've tried your code and it works. For the first one I'll try the work around they mentioned in the thread you referred me to. It kind of sucks that meteor does not currently have a way to support the first one – yusha uzumo Jul 11 '15 at 18:22
  • The work around in the thread is not dynamic at all. Also the way they plan to utilize the positional operator in mongo will most probably not cater for dynamism - sad! – yusha uzumo Jul 12 '15 at 05:18
  • yeah, I know. glad I could help though. – tomsp Jul 12 '15 at 07:07