How to create an output binding to cosmos db to create a new document using azure function.

Nischal Mainali 0 Reputation points
2024-11-08T07:12:03.95+00:00

I'm currently trying to send a sample document to Cosmos DB at the end of the function. Although the database and collection exist, it returns an error.

System.Private.CoreLib: Exception while executing function: Functions.cosmosTriggerCheck. Microsoft.Azure.WebJobs.Extensions.CosmosDB: The container 'reg-file-upload' (in database 'file-upload-transaction') does not exist. To automatically create the container, set 'CreateIfNotExists' to 'true'.

I have tried to use the option CreateIfNotExists but it sends a more cryptic error.

System.Private.CoreLib: Exception while executing function: Functions.cosmosTriggerCheck. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: NotFound (404); Substatus: 0; ActivityId: 39404a18-8510-4182-95a9-c71170f0f4f6;

I am following the example from this link, https://learn.microsoft.com/en-us/azure/azure-functions/functions-add-output-binding-cosmos-db-vs-code?pivots=programming-language-javascript

import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from "@azure/functions";

const sendToCosmoDb = output.cosmosDB({
  connection: "CosmosDbConnectionSetting",
  databaseName: "file-upload-transaction",
  containerName: "reg-file-upload",
});

export async function cosmosTriggerCheck(
  request: HttpRequest,
  context: InvocationContext
): Promise<HttpResponseInit> {
  context.log(`Http function processed request for url "${request.url}"`);

  const name = request.query.get("name");
  const descripttion = request.query.get("desc");

  context.extraOutputs.set(sendToCosmoDb, { name: name, descripttion: descripttion });

  return { body: `The api is up and running, ${name}!` };
}

app.http("cosmosTriggerCheck", {
  methods: ["GET"],
  authLevel: "anonymous",
  handler: cosmosTriggerCheck,
  extraOutputs: [sendToCosmoDb],
});

Also this is my host.json file contents

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "extensions": {
    "cosmosDB": {
      "connectionMode": "Gateway"
    }
  }
}
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,157 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,681 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Pinaki Ghatak 4,765 Reputation points Microsoft Employee
    2024-11-08T10:33:20.2033333+00:00

    Hello @Nischal Mainali

    It seems like the container 'reg-file-upload' in the database 'file-upload-transaction' does not exist.

    To automatically create the container, you can set 'createIfNotExists' to 'true'.

    You can try the following code snippet to create a new document in Cosmos DB using an output binding:

    import { AzureFunction, Context } from "@azure/functions";
    import { CosmosClient } from "@azure/cosmos";
    const endpoint = process.env.CosmosDbEndpoint;
    const key = process.env.CosmosDbKey;
    const client = new CosmosClient({ endpoint, key }); 
    const databaseName = "file-upload-transaction"; 
    const containerName = "reg-file-upload"; 
    const cosmosTriggerCheck: 
    AzureFunction = async function (context: Context, req: any): Promise {
    	const name = req.query.name; 
    	const description = req.query.description; 
    	context.bindings.outputDocument = {
    		name: name, description: description
    	};
    	context.res = { body: `The api is up and running, ${name}!` }; 
    };
    export default cosmosTriggerCheck;
    

    In the above code snippet, we are using the CosmosClient class from the @azure/cosmos package to create a new document in Cosmos DB. We are also using an output binding to write the document to Cosmos DB. The outputDocument binding is declared in the function.json file as follows:

    { 
    	"name": "outputDocument",
    	"type": "cosmosDB",
    	"databaseName": "file-upload-transaction",
    	"collectionName": "reg-file-upload",
    	"createIfNotExists": true,
    	"connectionStringSetting": "CosmosDbConnectionSetting",
    	"direction": "out"
    }
    

    Make sure to replace the CosmosDbConnectionSetting with the name of your Cosmos DB connection string setting in the local.settings.json file. Also, make sure to replace the databaseName and collectionName with the names of your database and collection respectively. Let me know if this helps!


    I hope that this response has addressed your query and helped you overcome your challenges. If so, please mark this response as Answered. This will not only acknowledge our efforts, but also assist other community members who may be looking for similar solutions.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.