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.