findOneAndUpdate - Update the first object in arra

2020-03-07 05:12发布

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'
         };

1条回答
▲ chillily
2楼-- · 2020-03-07 05:32

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
    }
});
查看更多
登录 后发表回答