Skip to content

Set default value (or empty list/dict) no longer unset the field - #2928

Merged
bagerard merged 7 commits into
MongoEngine:masterfrom
bagerard:set_empty_field_no_longer_unset
Aug 30, 2026
Merged

Set default value (or empty list/dict) no longer unset the field#2928
bagerard merged 7 commits into
MongoEngine:masterfrom
bagerard:set_empty_field_no_longer_unset

Conversation

@bagerard

Copy link
Copy Markdown
Collaborator

This fixes an awkward historical behavior of mongoengine. Fields that have falsy, non-numeric default values would be unset upon saving.

Typically:

  class UserProfile(Document):
      display_name = StringField(default="")
      interests = ListField(StringField())


  UserProfile.drop_collection()

  profile = UserProfile(
      display_name="Alice",
      interests=["reading", "cycling"],
  ).save()

  profile.display_name = ""
  profile.interests = []
  profile.save()

  print(UserProfile.objects.as_pymongo())

Historically would remove the fields from the documents
[{"_id": ObjectId("...")}]

And will now produce:
[{'_id': ObjectId('...'), 'display_name': '', 'interests': [ ] } ]

Fixes #267
Fixes #761
Relates to #2342
closes 2517

@bagerard
bagerard merged commit 407b1bb into MongoEngine:master Aug 30, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

item_frequencies returns {None: 1} if there's a single document with an empty list Confusing behaviour when ListFields are set to empty list

1 participant