How to perform both a $set and a $push in the same update query?

Hello guys,

Anyway to do the 2 updates in one query?

Both queries do not work, they don’t throw an error but they don’t work.

return Games.update(game._id, {
  $set: {
    player2: null,
    $push: {
    kickedOutUsers: game.player2
    }
  }
});
return Games.update(game._id, {
  $set: {
    player2: null
  },
  $push: {
    kickedOutUsers: game.player2
  }
});

Thanks

The second one is actually a valid query. Don’t know why that would not work.

The second only sets player2 to null, it does not adds the new player to the array.

Then the error must lie elsewhere because that is a valid query.

You made sure that game.player2 isn’t null and that kickedOutUsers actually is an array?

1 Like

I just tested it on and the following works

Items.update(item._id,{
	$set: {string:'axdf'},
	$inc:{count:1},
	$push:{random: Random.id()}
});

2 Likes

True.
It does not work for me because I am trying to $set a propeuerty to null,
The thing is that I need to $set the property as null and not $unset it.

I just changed my code to $set:{string: null} and it still works. Are you using aldeed:collection2 or simps-schema package or any other middleware? It believe it automatically sanitizes null values, unless instructed otherwise.

1 Like

Yes, I am using aldeed:collection2

Yes, I am using aldeed:collection2

I did the following and it works:


      return Games.update(game._id, {
        $set: {
          player2: null
        },
        $push: {
          kickedOutUsers: game.player2
        }
      },
      { validate: false }
      );

Thanks for guiding me in the right direction.

If you’re also using simpl-schema, there is a way to instruct it to treat null values. That way you could still have collection2 validate …

1 Like

Yes, I am also using simple-schema too. How can I do that?

If you use the npm package version, check out Set Default Cleaning Options, it might do what we are talking about

1 Like