mongoDB-创建不匹配ReferenceField的文档

时间:2018-07-23 09:48:48

标签: python mongodb one-to-many mongoengine flask-mongoengine

我正在使用Python 3.6,Flask和Mongoengine构建一个Web应用程序,该应用程序中有2个类。

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)

我正在尝试在PayMethodsExpense之间建立一对多关系 (Expense应该只有1个PayMethod,而只有1个PayMethod可以与许多Expenses相关。)

我注意到我可以使用无效的Expense创建一个新的PayMethod文档,这意味着一个表示PayMethod的JSON在数据库中尚不存在。 这怎么可能?数据库为何不强制执行这种关系并且不允许执行此操作?

这是我尝试做的,新的对象数据:

z = {'amount': 200, 'description': 'Random stuff', 'pay_method': ObjectId('5b7859092c88840c33a0a5b8'), 'timestamp': 'Sun, 19 Aug 2018 16:10:41 GMT'}

没有PayMethod和ID 5b7859092c88840c33a0a5b8

将新对象保存到数据库:

Expense(**z).save()
<Expense: Expense object>

在尝试访问文档PayMethod时:

c.pay_method

Traceback (most recent call last):
  File "/Users/shlomilanton/workscpace/slots_tracker_server/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2961, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-16-1150ff374ac6>", line 1, in <module>
    c.pay_method
  File "/Users/shlomilanton/workscpace/slots_tracker_server/venv/lib/python3.6/site-packages/mongoengine/fields.py", line 1076, in __get__
    raise DoesNotExist('Trying to dereference unknown document %s' % value)
mongoengine.errors.DoesNotExist: Trying to dereference unknown document DBRef('pay_methods', ObjectId('5b7859092c88840c33a0a5b8'))

我做错了什么?

0 个答案:

没有答案