Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

475
Views
How to initialize cosmosDB databases and containers in azure functions using the node sdk?

In my current implementation I have database initialization code that gets run on every function request, which is bad for performance reasons.

How to check if a container exists in cosmos DB using the node sdk?

It's best to create static connections on app initialization as described here: https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections#static-clients

but I'm having a bit of trouble with the initialization. Here is how the documentation describes it in javascript.

const cosmos = require('@azure/cosmos');
const endpoint = process.env.COSMOS_API_URL;
const key = process.env.COSMOS_API_KEY;
const { CosmosClient } = cosmos;

const client = new CosmosClient({ endpoint, key });
// All function invocations also reference the same database and container.
const container = client.database("MyDatabaseName").container("MyContainerName");

module.exports = async function (context) {
    const { resources: itemArray } = await container.items.readAll().fetchAll();
    context.log(itemArray);
}

The issues/questions I'm having are how do I do error handling if the database does not exist or if the container does not exist.

Do I need to separate my "createIfNotExists" logic from the functions app entirely?

If I try to run the createIfNotExists code on startup, I'm not able to do top level awaits and I have been getting promise rejections errors.

I'd like to do something like the following:

try
{
  const cosmos = require('@azure/cosmos');
  const endpoint = process.env.COSMOS_API_URL;
  const key = process.env.COSMOS_API_KEY;
  const { CosmosClient } = cosmos;

  const client = new CosmosClient({ endpoint, key });
  const db = await client.databases.createIfNotExists({id: "databaseId"});
  const container1 = await db.container.createIfNotExists(containerDefinition1)
  const container2 = await db.container.createIfNotExists(containerDefinition2)
}
catch(err)
{
  handleError(err)
}

...

module.exports = async function (context) {
    ...
    const {resources: items } = await container1.items.query(querySpec).fetchAll();
}


What's the best way to implement this? Any help is appreciated!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I think you need to handle each individually, for example

  async onApplicationLoad() {
        // Create DB if it doesn't exist
        try {
            await this.client.databases.createIfNotExists({ id: this.mDBId });
        } catch (error) {
            Logger.log(`Error creating database: ${error}`, 'AzureCosmosDbService');
        }
  
        // Create the containers if they don't exist
        try {
            await this.client.database(this.mDBId).containers.createIfNotExists({ id: this.mNoteContainerId });
            await this.client.database(this.mDBId).containers.createIfNotExists({ id: this.mReportedNotesContainerId });
  
            const iterator = this.client.database(this.mDBId).containers.readAll();
            const { resources: containersList } = await iterator.fetchAll();
        } catch (error) {
            Logger.log(`Error creating containers: ${error}`, 'AzureCosmosDbService');
        }
        return;
      }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!