Search code examples
azure-cosmosdbazure-cosmosdb-sqlapi

Have CosmosDB choose the ID of the inserted item


In a CosmosDB SQL API instance, i want to insert a simple JSON object in my container, let's say

{
    "first_name":"John",
    "last_name":"Doe"
}

With the sample app provided on azure, i do the following in Python :

container.create_item(body=snapshot)

I encouter this error, which seems fair enough :

run_sample has caught an error. (BadRequest) Message: {"Errors":["The input content is invalid because the required properties - 'id; ' - are missing. Learn more: https:\/\/aka.ms\/CosmosDB\/sql\/errors\/missing-id"]}

I don't want to provide the id but instead let the CosmosDB instance choose it, like many others systems can do (postgres, mongo...).

While i can do this in a CosmosDB MongoDB API instance, i can't do it with a SQL API Instance. Can this be achieved ?

I have the following settings for this collection :

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/*"
        }
    ],
    "excludedPaths": [
        {
            "path": "/\"_etag\"/?"
        }
    ]
}

Solution

  • Cosmos SQL API does not have any automatic id generation. This is referenced in the aka.ms link in the error you are sharing: https://aka.ms/CosmosDB/sql/errors/missing-id

    There is no setting or configuration you can turn on to achieve this. The id field needs to be generated and populated on your application code.

    Some older SDKs did a local autogeneration by assigning a Guid to the id but this is easily achievable on your application code.

    In NodeJS (the language you seem to be using) you could leverage the NodeJS crypto.randomUUID method (https://nodejs.org/docs/latest-v14.x/api/crypto.html#crypto_crypto_randomuuid_options) to generate a random Guid and assign it to the id property or use your own custom business logic.