0

I have a document structured like this:

{
    "_id" : ObjectId("555d93b52804d78810c20867"),
    "username" : "my user",
    "myClub" : {
        "myPlayers" : [ 
                {
                    "_id" : ObjectId("555d93b52804d78810c20868"),
                    "skill" : 55,
                    "stamina" : 50,
                    "moral" : 100,
                    "pos" : null,
                }, 
                {
                   "_id" : ObjectId("555d93b52804d78810c20868"),
                    "skill" : 55,
                    "stamina" : 50,
                    "moral" : 100,
                    "pos" : null,
                }, 
                ...

I want to do an update like this:

i have 5 documents like this, i want to update the number 55 in skill to 60 (add plus 5 to the current number) in all "myPlayers" array, but with the following conditions:

I want the max number to update to be 100 and only for those who have the pos to be null, which means if i have this:

 "_id" : ObjectId("555d93b52804d78810c20868"),
                "skill" : 100,
                "stamina" : 50,
                "moral" : 100,
                "pos" : null

I dont want a plus 5 on it.

What is the code i need to apply to handle this? I have something almost similar when i want to add object to all my documents:

this.model('User').update({},{ '$push': { 'myClub.myPlayers': {another user obj here }}},{multi:true ,upsert:true},function(err,numEffected){
        console.log('addPlayer, numEffected:',numEffected);
    });

Is it something similar to that one?

totothegreat
  • 1,633
  • 4
  • 27
  • 59
  • As suggested in the following post, it is not possible to update multiple array elements by one operation in mongodb. http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb – cubbuk May 21 '15 at 17:44

1 Answers1

1

Try querying the User mongoose model for myPlayers array with the given criteria and use the resulting cursor to update the skill field for each array element:

var query = {
    "myClub.myPlayers.pos": {"$eq": null}, 
    "myClub.myPlayers.skill": {"$lt": 100}
}, opts = {};
User.find(query, opts, function (err, res){
    if (err) return handleError(err);
    res.forEach(function (err, doc){
        if (err) return handleError(err);
        for(var i in doc.myClub.myPlayers){
            if(doc.myClub.myPlayers[i].skill < 100){
                doc.myClub.myPlayers[i].skill += 5;
            }
        }
        doc.save();
    });   
});
chridam
  • 100,957
  • 23
  • 236
  • 235
  • I have a collection named user, how can i find all (all collection) and do what you do here? when i do foreach on find says undefined: mongoose.model('User').find({}).forEach(function (doc){ console.log('doc',doc); }); //gives me error – totothegreat May 21 '15 at 12:20