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


#1

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


#2

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


#3

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


#4

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?


#5

I just tested it on and the following works

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


#6

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.


#7

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.


#8

Yes, I am using aldeed:collection2


#9

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.


#10

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 …


#11

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


#12

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