Insert a document with UUID instead of ObjectID for the _id field

I would like to use an Atlas Function to insert a new document into a collection. The _id field of the document should be a V4 UUID instead of an ObjectID because the client applications that access this collection (via the Realm Swift SDK) use UUID instead of ObjectID.

How can I do this?

I tried generating a UUID, base64-encoding it, then using this:

var newDoc = {
   _id: BSON.Binary.fromBase64(someUUID, 4),
   foo: "bar"

When I test the function, Atlas tells me a Document was inserted. But when I then try to view the collection in the UI on the web, the page hangs at “loading documents” and eventually tells me the query failed—as if the _id field is corrupted or in the wrong format. To recover, I have to delete and recreate the entire Collection.

Additional Context

When I insert a Document from the client application, it shows up like this in the web UI:

But if I attempt to insert a Document from the webUI itself, there is no option to set the type of the _id field to UUID():

How do I obtain the same result when adding Documents from Atlas Functions (and the web UI) as I do when adding them from the client application?

1 Like