No error when using ReferenceField to a document that doesn't exists

9 views
Skip to first unread message

Shlomi Lanton

unread,
Jul 30, 2018, 10:33:08 AM7/30/18
to MongoEngine Developers
I'm trying to create a One-To-Many relationship between 2 document (classes), but I saw that I can create a new document with reference to another document that doesn't exist yet in the DB. 
Why is that? Shouldn't mongo enforce this relationship by making sure that the connected document exists before creating the new document? is there a flag that I should use to get this functionality?

Code example:
I have the following 2 classes:

class PayMethods(BaseDocument):
    name = StringField(required=True, max_length=200, unique=True)

class Expense(BaseDocument):
    amount = IntField()
    descreption = StringField(required=True, max_length=200)
    pay_method = ReferenceField(PayMethods, required=True)

In the DB I have the following `PayMethod` documents and no `Expense` documents:
{
    "_id" : ObjectId("5b5c8a2b2c88848042426dfd"),
    "name" : "MasterCard"
}

Now I create a new document:
Expense(amount=1, descreption='Test', pay_method=ObjectId("4c4c8a2b2c88848042426dfd"))

I expected to get an error message at that point, but it doesn't happen and I successfully create this document.

I'm Using:
Python 3.6
flask
mongoengine
flask-mongoengine


Reply all
Reply to author
Forward
0 new messages