2

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.

1 Answer 1

2

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}})
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that was it. Thank you sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.