Skip to content

Confusing behaviour when ListFields are set to empty list #267

Open
@gareth-lloyd

Description

@gareth-lloyd
import mongoengine
class TestDoc(mongoengine.Document):
    list_field = mongoengine.ListField()

mongoengine.connect('test')
test_doc = TestDoc.objects.create()

After this operation, in spite of the fact that list_field was not given any value, the BSON document in the collection has a corresponding field initialized to an empty list:

cluster-1:PRIMARY> use test
switched to db test
cluster-1:PRIMARY> db.test_doc.find()                                                                                              
{ "_id" : ObjectId("515c24a4c02c1c58d59f02c0"), "_types" : [ "TestDoc" ], "list_field" : [ ], "_cls" : "TestDoc" }   

I understand why initializing to empty list could be a good idea - it allows subsequent list operations on that field to succeed. However, in the light of this, the following behaviour seems wrong to me:

test_doc.list_field = []
test_doc.save()

This call causes mongoengine to issue an $unset command, removing list_field from the BSON document:

cluster-1:PRIMARY> db.test_doc.find()                                                                                              
{ "_id" : ObjectId("515c24a4c02c1c58d59f02c0"), "_types" : [ "TestDoc" ], "_cls" : "TestDoc" }

So ListFields, unlike other field types, get initialized to empty lists when no value is given, but setting a ListField to empty list causes it to be removed from the underlying BSON document.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions