0

I am using flask-mongoalchemy to do a demo, and here is a question confused me for a while. At first I create a class User

class Student(db.Document):
    '''student info'''
    name = db.StringField()
    grade = db.IntField(required=False, default=None)

Then, I use this DB and create some example, such as student1, student2...and so on。 Now, I change the default value of grade from None to 0

grade = db.IntField(required=False, default=0)

When I run query again, it raise error:

mongoalchemy.exceptions.BadValueException: Bad value for field of type "grade".  Reason: "Value is not an instance of <class 'int'>

SO, how to auto-update this field change? What I did now is to modify the value of age in database manualy.

McCree Feng
  • 179
  • 4
  • 12
  • Can you drop `student` collection manually and build again? Or run update query in the mongo shell to set grade=0 – Valijon Feb 16 '20 at 10:48
  • @Valijon Can update operation change the table default value? – McCree Feng Feb 17 '20 at 08:52
  • It can change if table meets requirements. In your case, perhaps once you create your `student` collection, MongoDB creates [$jsonSchema](https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/) for validation. Check it: `db.getCollectionInfos({name: "student"})` – Valijon Feb 17 '20 at 09:03

1 Answers1

1

First, to get the queries working as before set allow_none option on the field to True.

grade = db.IntField(required=False, default=0, allow_none=True)

That should allow documents having no value for grades to not trigger errors when unwrapped as python objects.

Next, make a migration that sets the default value for documents where grade is None to 0.

from mongoalchemy.session import Session

with Session.connect('mongoalchemy') as s:
    update = s.query(Student).filter(Student.grade == None).set(User.grade, 0)
    update.execute()

Lastly, switch the field declaration back to disallow None values for the grade.

Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81