0

Using moongoose for Node.js, I'm trying to go through each object in the "STEPS" array and decrease the stepid by 1. Using this schema below:

"appid": 1,
"steps": [
            {
                "name": "step4",
                "stepid": 4,
            },
            {
                "name": "step5",
                "stepid": 5,
            }               
         ],
"appname": "myapp"

Here's how I tried is using .update:

app.db.models.myApps.update(
        {'appid': 1, 'steps.stepid': { $gt: 3 }},
        { $inc: { 'steps.$.stepid': -1 } },
    { multi: true }
);

But I can't seem to get it to work correctly. I was able to play around with the code and get it to update but it would only update 1 of the objects in the array, whereas I would like it to go through each object in the array and decrease by 1.

Should I break it out and first use find and then update? The old dev in me says to do a for loop but I know that's not the right way to do it with node.

Any help or suggestions are greatly appreciated! Thanks!

sMyles
  • 2,418
  • 1
  • 30
  • 44

1 Answers1

0

Unfortunately this appears to be an issue with mongodb which does not support it.

Per: How to Update Multiple Array Elements in mongodb

And here: https://jira.mongodb.org/browse/SERVER-1243

For now a workaround would be this:

function convertDirectMessages(id, cb) {
    Conversation.collection.update(
        {'messages.context': 'direct'}, 
        {$set:{'messages.$.context': {type:'direct'}}}, 
        {safe:true, multi:true},
        function(err, updated) {
            if (err) return cb(err);
            if (updated) return convertDirectMessages(id, cb);
            cb();
        }
    );
}
convertDirectMessages(posted._id, this);
Community
  • 1
  • 1
sMyles
  • 2,418
  • 1
  • 30
  • 44