Unsetting property vs setting to null

Hi!

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!

I always prefer to have the key existing in the database because:

  1. anytime you need to look at data on the DB, it’s easier when the key is visible when trying to figure out things
  2. In any case, that you need that key on an index, specificity on that key uses the index instead of doing something like { $exists: false } which does not
1 Like

Indexes can be set to ‘sparse’. I guess that would do the job for { $exists: false }. https://docs.mongodb.com/manual/core/index-sparse/

To save space I just don’t set it and use $exists or just check the value with a regular find because it will return the same way if it’s not there without error. In the javascript side you can just do typeof myVar != undefined or myVar != undefined and you’ll be good to go

1 Like

You can force the use of the index with a hint but technically, it is useless because the docs you want included with the query are not included in the sparse index.