one of the objectives of mongoose has been to minimize the amount of data stored in mongo. ignoring undefined values and empty objects etc.
however this approach is inconsistent. for example, while empty objects are currently ignored, empty arrays are not. we should probably fix this.
the current approach also does not take into consideration other processes querying / updating your dataset which may lead to problems if it doesn't expect this behavior.
in the master branch (which will be mongoose 3.x) we have doc#to{Object,JSON} options which are configurable at the schema level. with this PR we can now set the minimize option to false at the schema level as well
var options = { toJSON: { minimize: false }};
new Schema({ empty: {} }, options);
var o = doc.toJSON();
o.empty == {}
but that will still only impact explicit calls of toObject/toJSON by application logic; mongoose will still send minimized data (non-empty objects) to the db.
_relates to #848_
Actually, at least in my tests, empty objects do seem to be persisted and for me the problem was only in toObject() (and toJSON()). +1 for getting this behavior consistent.
closing. schemas have the minimize
option now which can be used to override this behavior.
Does it means that we _can't_ save any empty object in the database ?
Because there is a tradeoff ... it means that we have to check everytime what is the actual value stored in the property ...
you can, just add the minimize: false option to your schema:
new Schema({..}, { minimize: false })
OMG! This took me 2 years to find this. Now to test if this works.
"but that will still only impact explicit calls of toObject/toJSON by application logic; mongoose will still send minimized data (non-empty objects) to the db."
This still seems to be the case. Can someone confirm this?
+1 Yes empty objects are not saved in DB.
Really annoying behavior. It'd be nice if it was more obvious in the docs.
Most helpful comment
you can, just add the minimize: false option to your schema:
new Schema({..}, { minimize: false })