bq_
bq_

Reputation: 61

findOneAndUpdate - Update the first object in array that has specific attribute

I have an object that has attributes. This includes an array of other Objects that have their own attributes.

Lobby:
  --> "a": "b"
  --> "c": "d"
  --> Players:[
         --> 0
           --> "x": "23"
           --> "status": "ready"
         --> 1
           --> "x": "54"
           --> "status": "open"
         --> 2
           --> "x": "16"
           --> "status": "open"

How would I go about updating the first Player Object that has "status": "open" (in this case 1) to a new object?

For example:

player = {
            x: "125",
            status: 'joined'
         };

Upvotes: 2

Views: 3570

Answers (1)

bq_
bq_

Reputation: 61

I managed to find a working solution!

Game.findOneAndUpdate({'a': 'b', 'Players.status': 'open'}, { $set : { 'Players.$': player} },
function (err, doc) {
    if (err) {
        console.log(err);
    } else {
        // Do stuff
    }
});

Upvotes: 4

Related Questions