Mongoengine: On update the model is not validated

Created on 2 May 2016  路  3Comments  路  Source: MongoEngine/mongoengine

Hi

For the following document model:

class Inventory(Document):
    store_id = StringField(required=True)
    product_sku = StringField(unique_with=['store_id'], required=True)
    is_product_enabled = BooleanField(default=False)
    stock = IntField(required=True, min_value=0, default=0)
    created_time = DateTimeField(default=datetime.now)
    updated_time = DateTimeField(default=datetime.now)

When running the following query to decrease the stock:

inventory_obj = Inventory.objects.get(product_sku=product_sku, store_id=store_id)
inventory_obj.update(dec__stock=10)

Document before the update:

{
    "_id" : ObjectId("57273c29aafbb3d5bf7b99f9"),
    "store_id" : "1",
    "product_sku" : "1",
    "is_product_enabled" : true,
    "ready_stock" : 7,
    "stock" : 6,
    "created_time" : ISODate("2016-05-02T17:08:17.452Z"),
    "updated_time" : ISODate("2016-05-02T17:26:39.756Z")
}

Post the update

{
    "_id" : ObjectId("57273c29aafbb3d5bf7b99f9"),
    "store_id" : "1",
    "product_sku" : "1",
    "is_product_enabled" : true,
    "stock" : -4,
    "created_time" : ISODate("2016-05-02T17:08:17.452Z"),
    "updated_time" : ISODate("2016-05-02T18:27:58.592Z")
}

The stock becomes negative. Is this the desired behaviour?
Is there a work around for validating the min_value?

Bug

Most helpful comment

I think ME's BaseQuerySet.update_one wraps ME's BaseQuerySet.update, which uses pymongo's update.

I don't think bypass_document_validation is used, here. Validation takes place in ME's validate prior to call to pymongo.

(That's my understanding from a quick look. I don't claim any expertise.)

All 3 comments

Code: save / update

Docs: save / update

AFAIU, update does not validate. It looks like a shortcoming rather than a design choice.

Should we modify update to call validate?

While we're at it, we may want to add a few of save's parameters:

  • validate
  • clean
  • write_concern
  • save_condition

AFAIU mongoengine update_one wraps pymongo update_one which takes a parameter bypass_document_validation which is by default False
Is bypass_document_validation getting set to True in mongoengine somewhere?

I think ME's BaseQuerySet.update_one wraps ME's BaseQuerySet.update, which uses pymongo's update.

I don't think bypass_document_validation is used, here. Validation takes place in ME's validate prior to call to pymongo.

(That's my understanding from a quick look. I don't claim any expertise.)

Was this page helpful?
0 / 5 - 0 ratings