From 4cca9f17dfa4065d1ab673fa01083a87fbfcf593 Mon Sep 17 00:00:00 2001 From: Rik Date: Mon, 2 Sep 2013 18:11:50 +0200 Subject: [PATCH] Check if undefined fields are supplied on document If an undefined field is supplied to a document instance, a `FieldDoesNotExist` Exception will be raised. --- mongoengine/base/document.py | 11 ++++++++++- mongoengine/errors.py | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py index df06f6ae..2def35f4 100644 --- a/mongoengine/base/document.py +++ b/mongoengine/base/document.py @@ -12,7 +12,7 @@ from bson.son import SON from mongoengine import signals from mongoengine.common import _import_class from mongoengine.errors import (ValidationError, InvalidDocumentError, - LookUpError) + LookUpError, FieldDoesNotExist) from mongoengine.python_support import PY3, txt_type from mongoengine.base.common import get_document, ALLOW_INHERITANCE @@ -61,6 +61,15 @@ class BaseDocument(object): signals.pre_init.send(self.__class__, document=self, values=values) + # Check if there are undefined fields supplied, if so raise an + # Exception. + for var in values.keys(): + if var not in self._fields.keys(): + msg = ( + "The field '{}' does not exist on the document '{}'" + ).format(var, self._class_name) + raise FieldDoesNotExist(msg) + if self.STRICT and not self._dynamic: self._data = StrictDict.create(allowed_keys=self._fields_ordered)() else: diff --git a/mongoengine/errors.py b/mongoengine/errors.py index 4b6b562c..990150da 100644 --- a/mongoengine/errors.py +++ b/mongoengine/errors.py @@ -40,6 +40,10 @@ class NotUniqueError(OperationError): pass +class FieldDoesNotExist(Exception): + pass + + class ValidationError(AssertionError): """Validation exception.