hmarr/mongoengine — Issue #405: BooleanField(default=False) results in no value in mongodb in specific circumstances
Author: djziegler
Created: 2012-01-05 18:22:28+00:00
State: open

```python

"""
Demonstrate an obscure bug with BooleanField(default=False).

1) Create an object with a BooleanField(default=False) and persist it.
2) Load the object and set the field value to False again, then save the object.

BUG: mongodb will no longer have have a field at all. This messes up indexes etc.

If there is no default, or if default=True, there does not appear to be a problem.

Workaround: don't use BooleanField(default=False).
"""

from mongoengine import *
import sys

class Dog(Document):
name = StringField ()
friendly = BooleanField(default=False)

def test ():
connect ('testdb')

Dog.drop_collection ()

# Create a dog
rover0 = Dog (name='Rover')
rover0.friendly = False # Makes no difference if we do this line or not.
rover0.save ()

print '*** In this dump both mongoengine and mongodb agree that the dog is unfriendly'
dumpDogs ()

# Load and re-set friendly field, then resave (this is where the value is getting lost)
rover1 = Dog.objects(name='Rover').get ()
rover1.friendly = False
rover1.save ()

print '*** Whoops: now mongoengine thinks the dog is unfriendly, but mongodb doesn\'t have the field'
dumpDogs ()

# This line will not find the dog (if you turn it on)
if False:
rover2 = Dog.objects(friendly=False).get ()
print rover2

def dumpDogs ():
print 'Mongoengine view of dogs'
for e in Dog.objects ():
print ' ', 'name = ', e.name, 'friendly =',e.friendly, e.to_mongo()
print 'Mongodb view of dogs'
for o in Dog.objects._collection.find ():
print ' ', o
print
print

if __name__ == '__main__':
test ()

```