Home > Enterprise >  How to connect to an Azure CosmoDB for MongoDB from an Azure Function
How to connect to an Azure CosmoDB for MongoDB from an Azure Function

Time:04-22

I'm starting in Azure Function & Cosmo DB. I created in the Azure Portal a function app, then I followed the guide to get started in VS Code:

npm install -g azure-functions-core-tools@4 --unsafe-perm true
Then New Project
Then New function, selected the HTTP trigger template

When running F5 and deployed, it work.

Then I created, in the portal, a "Azure Cosmos DB API for MongoDB" database. I followed this to publish a document when having my method called:

https://docs.microsoft.com/en-us/azure/azure-functions/functions-add-output-binding-cosmos-db-vs-code?tabs=in-process&pivots=programming-language-csharp

So my current result is: a function:

namespace TakeANumber
{
   public static class TestFunc
   {
      [FunctionName("TestFunc")]
      public static async Task<IActionResult> Run(
          [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
          [CosmosDB(databaseName: "cosmodb-take-a-number", collectionName: "take-a-number", ConnectionStringSetting = "cosmoDbConnectionString")] IAsyncCollector<dynamic> documentsOut,
          ILogger log)
      {
         log.LogInformation("C# HTTP trigger function processed a request.");

         string name = req.Query["name"];

         string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
         dynamic data = JsonConvert.DeserializeObject(requestBody);
         name = name ?? data?.name;

         string responseMessage = string.IsNullOrEmpty(name)
             ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
             : $"Hello, {name}. This HTTP triggered function executed successfully.";
             
         if (!string.IsNullOrEmpty(name))
         {
            // Add a JSON document to the output container.
            await documentsOut.AddAsync(new
            {
               // create a random ID
               id = System.Guid.NewGuid().ToString(),
               name = name
            });
         }
         return new OkObjectResult(responseMessage);
      }
   }
}

A local.settings.json file with a cosmoDbConnectionString settings that contains a mongo db connexion string.

When I run the function, I get this:

[2022-04-21T17:40:34.078Z] Executed 'TestFunc' (Failed, Id=b69a625c-9055-48bd-a5fb-d3c3b3a6fb9b, Duration=4ms)
[2022-04-21T17:40:34.079Z] System.Private.CoreLib: Exception while executing function: TestFunc. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'documentsOut'. Microsoft.Azure.DocumentDB.Core: Value cannot be null. (Parameter 'authKeyOrResourceToken | secureAuthKey').

My guess is that it's expecting a Core SQL database, with another kind of access token. My question: Is it possible to connect to an azure CosmoDB for MongoDB from an Azure function?

CodePudding user response:

If you're using out-of-the-box bindings, you can only use Cosmos DB's SQL API.

You can totally use the MongoDB API, but you'd have to install a MongoDB client SDK and work with your data programmatically (just like you'd do with any other code-oriented approach).

Since your sample code is taking data in, and writing out to Cosmos DB, you'd do your writes via MongoDB's node/c#/python/etc driver (I believe they still call them drivers), which effectively gives you a db.collection.insert( {} ) or something more complex.

More info about Cosmos DB bindings here.

  • Related