htmlnode.jsmongodbmeteorsimple-schema

Meteor Unsetting property vs setting to null


I have some fields (a timestamp and userId) that exist on a Collection and will either exist or not based on a Checkbox input.

If the user checks off the box, the properties gets saved with their Date and Time fields.

However, upon unchecking, I'm simply updating the property to null (as opposed to unsetting). On the frontend, my Helpers see the null value and don't display the timestamp and userId (which is good). But, I'm concerned with the property still existing on the Document (albeit being set to null)

I thought SimpleSchema would see the null value and remove the Property, but I am wrong. Any foreseeable issues with doing it this way, or is it better off to be safe and make a separate unset call to just remove the properties themselves?

Thanks!


Solution

  • As far as I'm aware $unset is the way to do this.

    There isn't anything inherently "wrong" with setting the property to null in your DB. In fact I used to rely on this pattern quite a bit to differentiate between null data and data that straight up wasn't present.

    I've since come to prefer either the data having a value (Date, String, etc) or not being set a la $unset as it:

    1. makes the DB read cleaner in a GUI by not showing fields that aren't present at all making better use of the viewport
    2. still allows most of the same JS Boolean coercion logic such as !theThing.theProperty
    3. keeps null as a concept more pure and reserved for instances where null is truly different to your application code than undefined. These tend to be infrequent but I've definitely run into them.
    4. Mongo (and more specifically Meteor's integration with Mongo) have some nuanced query behaviors around null vs undefined that aren't exactly the most intuitive thing to a newer dev in the stack and setting properties to null as opposed to undefined somewhat plays into that.