Need help on connecting Azure Cosmos DB using Java script.

Junheok Cheon 40 Reputation points
2024-10-08T10:16:21.2066667+00:00

Hello,

I have just started on using cosmos DB.
My goal is to create a java script app where I can store audit logs into cosmos DB.

But I have some problems related to adding new items in the container.

I ran this following code I provided, but it seems like the item is not being saved in the container.

I also get this following error:
User's image

Looking at this console, I would assume it is the last part of my code that is being problematic, but I can't find a reason why. I would like to have some insight on how to this properly.

Thanks.

try {
    // Set up the Cosmos client
    const cosmosClient = new CosmosClient(cosmosDBConnectionString);
    console.log("CLIENT SET UP");

    // Access the database and container
    const container = cosmosClient.database(cosmosDbId).container(cosmosContainerId);
    console.log("CONTAINER ACCESSED");

    // Create an item in the container
    const statusCode = await container.items.create(auditLogObject);
    console.log("ITEM CREATED: ", statusCode);
  } catch (error) {
    console.error("ERROR PUSHING DATA INTO COSMOS DB: ", error);
  }
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,672 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Mahesh Kurva 725 Reputation points Microsoft Vendor
    2024-10-08T17:28:04.5766667+00:00

    Hi @Junheok Cheon,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.The error message suggests that an unexpected token 'U' was encountered in JSON at position 0, indicating a problem with the creation or parsing of the JSON object.

    To resolve this problem, you can try the following:

    • Ensure that the auditLogObject is a valid JSON object. You can use the JSON.stringify() method to convert the object to a string and then log it to the console to verify its structure.
    • The id property in Cosmos DB must be a string. You're currently setting it to new Date(), which is an object. You should convert it to a string format. You could use something like new Date().toISOString() or any other unique string identifier.
    • Ensure that your cosmosDBConnectionString is correctly formatted and that you have the necessary permissions to write to the container.
    • Ensure that the environment you're running this code in supports async/await. If this code is not inside an async function, it won't work as expected. Wrap the code in an async function if it's not already.
    • Ensure that the structure of auditLogObject matches the container's schema (if any). Although Cosmos DB is schema-less, it's a good practice to maintain a consistent structure.

    Here is an example of how you can modify your code to include these steps:

    async function logAudit() {
        try {
            const cosmosClient = new CosmosClient(cosmosDBConnectionString);
            console.log("CLIENT SET UP");
            const container = cosmosClient.database(cosmosDbId).container(cosmosContainerId);
            console.log("CONTAINER ACCESSED");
            const auditLogObject = {
                id: new Date().toISOString(),
                action: actionType,
                actor: actorInformation,
                value: value
            };
            const { resource: createdItem } = await container.items.create(auditLogObject);
            console.log("ITEM CREATED: ", createdItem);
        } catch (error) {
            console.error("ERROR PUSHING DATA INTO COSMOS DB: ", error);
        }
    }
    logAudit();
    

    Hope this helps. Do let us know if you any further queries.

    If this answers your query, do click Accept Answer and Yes for was this answer helpful. And, if you have any further query do let us know.

     


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.