Home > Blockchain >  How to use object as filter in findOneAndUpdate in mongodb
How to use object as filter in findOneAndUpdate in mongodb

Time:11-05

I want to use _id object as filter in findOneAndUpdate:

{
    "_id": {
        "playerId": "189583",
        "tournamentId": "197831"
    },
    "playerName": "Afiridi",
    "score": [],
    "__v": 0
}

I tried this but it didn't work:

await Scorecard.findOneAndUpdate(
{
      _id: {
        playerId: playerId,
        tournamentId: tournamentId
      }
    },
    {
      $addToSet: {
        "score": {
          _id: matchID
        }
      }
    }
  );
//playerId and tournamentId are coming from above code, not listed

I am using mongoose, but any kind of help is appreciated.

CodePudding user response:

Try the dot-notation syntax:

await Scorecard.findOneAndUpdate(
        {
          "_id.playerId": playerId,
          "_id.tournamentId": tournamentId
        },
        {
          $addToSet: {
            "score": {
              _id: matchID
            }
          }
        }
      );
  • Related