Resolving Error in Mongo: “Cannot create field ‘None’ in element”

Article summary

Recently, I was working with a non-relational database for the first time. I kept running into the error: Cannot create field ‘None’ in element. It looked like this:

“Cannot create field 'None' in element {someKey: “my precious data”}” 

The Code

Seemingly, this error was coming from the model code in my Flask app, which interacted with the Mongo database via PyMongo. The code I was using looked something like this:


def add_new_item(self, document_id: str, section_ID: int, subsection_ID: int, rich_content: str):
        new_item = {
            "content": rich_content,
        }
        content_path = "part.of.path." + str(section_ID) + ".of." + str(subsection_ID)
        collection(COLLECTION_PATH).update_one(
            {"_id": document_id},
            {
                "$push": {content_path: new_item},
            },
        )       

The Problem

It turns out the problem was caused by the variables I was using in the content path being “None” aka, undefined. The controller code that was calling this method was not sending in the section_ID correctly. This means Mongo did not understand where to put the content in the document.

The Fix

I fixed this by correcting the problem in my controller.  Further, I also changed the parameter of the method to have a default value. You can do this in Python like so:


def add_new_item(self, document_id: str, section_ID: int = 0, subsection_ID: int = 0, rich_content: str): 

While I was trying to debug this, I kept looking at the rich content I was passing into the database, thinking the problem must have been there. Once I expanded my thinking to consider the path as well, the issue became much clearer.

Updating the insert path to make sure that items have a valid place before inserting them is the main takeaway. I hope this helps you if you encounter this issue. Additionally, it can be helpful to examine the update_one result object, which is a Mongo UpdateResult, if you’re still having problems. You can find that here: Docs for PyMongo update result.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *