[파이썬] mongoengine 고급 검증 기법

Mongoengine is a Python Object-Document Mapping (ODM) library that provides an elegant way to work with MongoDB databases. It allows you to define your data models using Python classes and perform various operations on the database using those models.

One important aspect of working with any database is ensuring the data’s accuracy and validity. In this blog post, we will explore some advanced validation techniques provided by Mongoengine to enforce data integrity in your MongoDB collections.

Validation with Field Constraints

Mongoengine allows you to define field constraints on your data models to ensure that certain conditions are met before the data is saved to the database. These constraints can be specified directly in the field definition or using the validators argument.

Here is an example of a data model with field constraints:

from mongoengine import Document, StringField, IntField

class User(Document):
    name = StringField(required=True, max_length=100)
    age = IntField(min_value=0, max_value=120)

In the example above, the name field is required and must be less than or equal to 100 characters long. The age field must be an integer between 0 and 120.

Custom Validation

Sometimes, the default field constraints are not enough, and you need to perform custom validation on your data. Mongoengine allows you to define custom validation methods using the validation decorator.

Here is an example of a custom validation method:

from mongoengine import Document, StringField
from mongoengine.errors import ValidationError

class User(Document):
    name = StringField(required=True)

    def clean(self):
        if len(self.name) < 3:
            raise ValidationError("Name must be at least 3 characters long.")

In the example above, the clean method is decorated with the validation decorator. It checks if the length of the name field is less than 3 characters and raises a ValidationError if it is.

Pre and Post-Save Hooks

Mongoengine provides pre and post-save hooks that allow you to perform additional actions before or after a document is saved to the database. These hooks can be useful for performing complex validations or modifying the data before persisting it.

Here is an example of a pre-save hook:

from mongoengine import Document, StringField
from mongoengine.signals import pre_save

class User(Document):
    name = StringField(required=True)

def pre_save_user(sender, document, **kwargs):
    if "@" not in document.name:
        document.name = document.name + "@example.com"

pre_save.connect(pre_save_user, sender=User)

In the example above, the pre_save_user function is connected to the pre_save signal of the User document. It checks if the name field contains the “@” symbol and appends it if it doesn’t. This ensures that all user names have an email domain.

Conclusion

In this blog post, we have explored some advanced validation techniques provided by Mongoengine for ensuring data integrity in your MongoDB collections. By using field constraints, custom validation methods, and pre/post-save hooks, you can enforce various validation rules and modify the data before it is saved to the database.

Mongoengine’s validation capabilities give you fine-grained control over your data, allowing you to build robust and reliable applications. So, next time you work with MongoDB using Mongoengine, remember to leverage these advanced validation techniques to ensure the accuracy and validity of your data.