mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

NotUniqueError on field with unique=False

Open marcelodiaz558 opened this issue 4 years ago • 0 comments

Hi, I'm facing the following situation:

I have two classes:

1:EmbeddedDocument and the other is a 2: Document

Inside of the document I'm using a variable called products which is an EmbeddedDocumentListField to store objects of class 1, and on class 1 I'm having a primary key that uses an ObjectIdField, now the issue happens when I create two or more objects where the variable products = [] (when it's an empty list), in that situation I'm receiving a NotUniqueError, even when products is defined as non-unique.

The code:

class Image(EmbeddedDocument):
    """ Product with image schema """
    oid = ObjectIdField(required=True, default=ObjectId, unique=True, primary_key=True)
    image_url = StringField(required=True)


class ImageLibrary(Document):
    """ Library of images"""
    store_id = StringField(primary_key=True)

    products = EmbeddedDocumentListField("Image", unique=False)

    meta = {'db_alias': 'CMS_DB', 'allow_inheritance': True, 'collection': 'image_libraries'}

Testing:

image_library = {"store_id":store_id, "products":[]}
image_library = ImageLibrary(**image_library).save() # Saves correctly and returns the object with an ID

image_library = {"store_id":store_id, "products":[]}
image_library = ImageLibrary(**image_library).save() # Produces the error

The error:

mongoengine.errors.NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: 5c429_CMS_DEV.images_libraries index: products._id_1 dup key: { products._id: null }, full error: {'index': 0, 'code': 11000, 'keyPattern': {'products._id': 1}, 'keyValue': {'products._id': None}, 'errmsg': 'E11000 duplicate key error collection: 5c429_CMS_DEV.images_libraries index: products._id_1 dup key: { products._id: null }'})

There's any workaround for this? I understand that the problem is happening because the EmbeddedDocument class 1 has a unique object_id inside of it, but it should be independent of the EmbeddedDocumentListField which is non-unique.

marcelodiaz558 avatar Apr 15 '21 14:04 marcelodiaz558