Is it possible to update a subdocument via Mongoose using an $inc? Is it possible to update a subdocument via Mongoose using an $inc? mongoose mongoose

Is it possible to update a subdocument via Mongoose using an $inc?


Why do you put the $ operator inside another object. In javascript it ll become a associative array, but $inc accepts the string equivalent of it.

Try this function

Person.update {personName: "Some name"}, {$inc:  "metaDetails.$.visits" : 1 }, {upsert: true}, (err, updRes) ->


I'm not familiar with the Mongoose syntax as I generally use the native driver directly, but your JS update should look like:

db.Person.update({"personName": "Some name", "metaDetails.visits": {$exists: true}}, {"$inc": {"metaDetails.$.visits": 1}})

This might be analogous, I'm not sure (feels like there are missing brackets):

Person.update {personName: "Some name", $exists: "metaDetails.visits": true}, {$inc: "metaDetails.$.visits" : 1 }

Setting upsert to true will create a duplicate personName record if there is no metaDetails object with a visits key. Succinctly, the $ operator in the update requires that the field be part of the predicate.