How to connect to different databases inside a single Azure CosmosDB Account using Azure Functions.

Hament Pandya 1 Reputation point
2022-04-17T02:20:25.353+00:00

Hi,

I'm struggling with writing a JSON objects to one of multiple databases in a single CosmosDB account.

I'm using Javascript.

Scenario:

I have a single CosmosDB Account: "my-cosmosdb-account"

containing 3 databases e.g. (btw I wish to keep these databases separate for security reasons):

my_users_db
my_hobbies_db
my_pets_db

Each Database contains different containers:
my_users_db >> Containers > users, names, other_things
my_hobbies_db >> Containers > instruments, sports, entertainment
etc.

I wish to add different entries as follows using an Azure Function App (connected to API Managment):
my_cosmosdb_account > my_users_db > names
my_cosmosdb_account > my_hobbies_db > sports

The function app binding for the first scenario is:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": ["post"],
      "route": "user"
    },

    {
      "name": "outputDocument",
      "type": "cosmosDB",
      "databaseName": "my_users_db",
      "collectionName": "users",
      "createIfNotExists": true,
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "out",
      "createLeaseCollectionIfNotExists": true,
      "leaseCollectionName": "leases"
    },

    { "type": "http", "direction": "out", "name": "res" }
  ]
}

Problem: I keep getting a 500 Server Error.

Question: How do I connect the function to the account and then access a specific database and then a given container ? I'm sure Im missing something but haven't found the answer in the documentation so far.

Any help would be much appreciated.

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,518 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,506 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MayankBargali-MSFT 69,931 Reputation points
    2022-04-20T04:16:22.583+00:00

    @Hament Pandya Thanks for reaching out. To troubleshoot or monitor your function app you can always refer to this document which will help you to monitor azure function. Once you have set it up you can see more details of any error in your configured application insights. It looks like the binding is not setup correctly in your function app code or your CosmosDBConnection might be missing from configuration blade of your function app.

    As you want to leverage multiple output bindings then you need to create separate out binding name in your function.json and bind individual name that is defined in function.json in your function app. I have used v4 function with node js 14 for the test performed at my end and I don't see any issue with the code below and the I can see the data at my cosmos DB end.
    As I am using Node 14 I have defined WEBSITE_NODE_DEFAULT_VERSION value as ~14 in my function app.

    For your reference I have defined the multiple binding in my fuction.json as below

    {  
      "bindings": [  
        {  
          "authLevel": "anonymous",  
          "type": "httpTrigger",  
          "direction": "in",  
          "name": "req",  
          "methods": [  
            "get",  
            "post"  
          ]  
        },  
        {  
          "type": "http",  
          "direction": "out",  
          "name": "res"  
        },  
        {  
          "name": "myusersdb",  
          "type": "cosmosDB",  
          "databaseName": "MyDatabase",  
          "collectionName": "my_users_collection",  
          "createIfNotExists": true,  
          "connectionStringSetting": "MyAccount_COSMOSDB",  
          "direction": "out"  
        },  
        {  
          "name": "myhobbiesdb",  
          "type": "cosmosDB",  
          "databaseName": "MyDatabase",  
          "collectionName": "my_hobbies_collection",  
          "createIfNotExists": true,  
          "connectionStringSetting": "MyAccount_COSMOSDB",  
          "direction": "out"  
        },  
        {  
          "name": "mypetsdb",  
          "type": "cosmosDB",  
          "databaseName": "MyDatabase",  
          "collectionName": "my_pets_collection",  
          "createIfNotExists": true,  
          "connectionStringSetting": "MyAccount_COSMOSDB",  
          "direction": "out"  
        }  
      ]  
    }  
    

    index.js

    module.exports = async function (context, req) {  
        context.log('JavaScript HTTP trigger function processed a request.');  
      
        const responseMessage  = "This HTTP triggered function executed successfully."  
      
        context.bindings.myusersdb = JSON.stringify([  
            {  
                    "id": "John Henry-123456",  
                    "name": "John Henry",  
                    "address": "A town nearby"  
                },  
                {  
                    "id": "John Doe-123457",  
                    "name": "John Doe",  
                    "address": "A town far away"  
            }]);  
          
        context.bindings.myhobbiesdb = JSON.stringify([  
            {  
                        "id": "John Henry-123456",  
                        "hobby": "Reading",  
                },  
                {  
                        "id": "John Doe-123457",  
                        "hobby": "Writing",  
            }]);  
      
        context.bindings.mypetsdb = JSON.stringify([  
            {  
                            "id": "John Henry-123456",  
                            "pets": "Cat",  
                    },  
                    {  
                            "id": "John Doe-123457",  
                            "pets": "Dog"  
            }]);  
              
      
        context.res = {  
            // status: 200, /* Defaults to 200 */  
            body: responseMessage  
        };  
    }  
    

    **Note: ** Please modify the above as per your business requirement.

    I will suggest you to verify the application insights logs to know the root cause of 500 errors. But in case you are still facing the issue then please share your sample code along with configuration so I can validate it at my end and if needed we can connect offline.

    Feel free to get back to me if you need any assistance.

    Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.

    0 comments No comments