[BUG] Error occurs when saving to a model with the keep_nulls = False setting #1048
Open
Description
Describe the bug
When I call save() from document with the keep_nulls = False
setting:
pymongo.errors.OperationFailure: '$unset' is empty. You must specify a field like so: {$unset: {<field>: ...}}, full error: {'ok': 0.0, 'errmsg': "'$unset' is empty. You must specify a field like so: {$unset: {<field>: ...}}", 'code': 9, 'codeName': 'FailedToParse'}
This is happening because func get_top_level_nones return a empty dictionary when None-values is missing.
[{'$set': {'request_id': ...}}, {'$unset': {}}]
Expected result
The document with the keep_nulls = False
setting to save successfully even if there are no None-values
My solution
in method save from Document in branch if self.get_settings().keep_nulls is False
:
instead
if self.get_settings().keep_nulls is False:
return await self.update(
SetOperator(
get_dict(
self,
to_db=True,
keep_nulls=self.get_settings().keep_nulls,
)
),
Unset(get_top_level_nones(self)),
session=session,
ignore_revision=ignore_revision,
upsert=True,
**kwargs,
)
do this
if self.get_settings().keep_nulls is False:
arguments = [
SetOperator(
get_dict(
self,
to_db=True,
keep_nulls=self.get_settings().keep_nulls,
)
)
]
nones = get_top_level_nones(self)
if nones:
arguments.append(
Unset(nones)
)
return await self.update(
*arguments,
session=session,
ignore_revision=ignore_revision,
upsert=True,
**kwargs,
)