0

user1 in database

{
    counts: [{code:"aaa", num:100}, {code:"bbb", num:200}]
}

counts is an Array, it has two elements code and num.

How to let num increase 1 if code = "aaa"?

Meteor.users.update(user1._id, {$inc: {???}}); // How to write this?

Thanks

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267
  • 1
    As a note for meteor. Performing updates from the client (browser) without the main `_id` is considered insecure. As long as you include the `_id` as well as the element to to match in the query `{ "_id": user1._id, "counts.code": "aaa" }` then all should be fine. Anything else implies a multiple document update and is insecure, therefore should be defined as a server side method to be invoked. But the basic answer is include the element to match in the query portion of the update and reference with the positional `$` operator `{ "$inc": { "counts.$.num": 1 }}`.in the update portion. – Blakes Seven Feb 26 '16 at 22:32
  • @BlakesSeven thank you so much! – Hongbo Miao Feb 26 '16 at 23:09

1 Answers1

0

Gotta positionally match. Example:

Players.update({
  _id: Meteor.userId(),
  'games._id': Session.get('gameId')
}, {
  $inc: { 'games.$.score': 1 }
});
corvid
  • 10,733
  • 11
  • 61
  • 130