Pymongo: can a field type be enforced with insertOne?

This morning I got bitten by a stupid mistake. I have two similarly named python dictionary fields: articledata[‘editiondate’] which holds string values such as ‘20230505’ and articledata[‘dateISO’] which holds a datetime value.

By mistake I badly edited my program and wound up inserting new documents with a dateISO field which wrongly the string value and not the intended date value.

Is there a pymongo/mongodb way of raising an exception in cases such as this. A way of stating that a given field is of a given type? A way that if the above is not respected I can rais an exception and perhaps log what happened without actually inserting?

Thanks a lot

You can configure server side schema validation to prevent this kind of bug via: https://www.mongodb.com/docs/manual/core/schema-validation/specify-json-schema/#std-label-schema-validation-json

1 Like

Thanks a lot this is great!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.