Category: How do I do X?
Updated

This solution is summarized from an archived support forum post. This information may have changed. If you notice an error, please let us know in Discord.

How do I generate a unique _id for MongoDB embedded documents

Issue

I am having trouble allowing MongoDB to generate an _id for embedded documents. Even though I can add the embedded object and specify my own _id, leaving _id blank is causing an error. I need help letting MongoDB generate a unique _id for embedded documents.

Resolution

The issue is that the user wants to allow MongoDB to generate an _id for embedded documents when using the $push operation, but leaving the _id field blank gives an error. They have tried using ObjectId('') but it doesn't work. A suggested solution is to use new ObjectId() instead. However, there seems to be an error with the JSON reader when passing non-string commands in Appsmith.

It was later discovered that MongoDB does not allow the auto creation of unique _id for embedded objects/documents. Therefore, using ObjectId() for embedded documents will not work. The user may have to manually generate a unique _id before inserting the embedded document. This limitation is discussed in the MongoDB Developer Community Forums.