RSH
RSH

Reputation: 39

(MongoDB / Mongoose) Increment a value in an array of objects

I have a document that looks like this:

{
  "id": "12345",
  "channels": [
    {
      "id": "67890",
      "count": 1
    }
  ]
}

What I want to do is increment a given channel count by one. So a user sends a message and I look up the user, find the proper channel by "id" in the "channels" array, and increment "count" by one.

I tried the following query:

UserModel.findOneAndUpdate({id: this.id}, 
  {'channels.id': channel.id}, 
  {$set: {$inc: {'channels.$.count': 1}}}

It didn't fail, surprisingly. But it also didn't increment the count.

Upvotes: 2

Views: 361

Answers (1)

mickl
mickl

Reputation: 49945

Two fixes needed: query has to be a single object and $inc is a separate operator so you don't need $set:

UserModel.findOneAndUpdate({id: this.id, 'channels.id': channel.id},
    { $inc: {'channels.$.count': 1}})

Upvotes: 2

Related Questions