javascriptazure-cosmosdb

Item.Read does not work according to any of the provided docs


I have gone through all the types of documentation provided about the CosmosDB Read Item method. But it doesn't seem to work.

const item = container.item(id, undefined);
console.log("Read item '" + item.id + "'");
const { resource: readDoc } = await item.read();
console.log("item with id found: '", readDoc);

The ID I pass is '1' and there is a record with id '1' in the collection. It always return as undefined. Anybody already know how this works?

Here are the docs which I referred. (Read an item by ID : Item.read) https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-nodejs-samples


Solution

  • It seems that you pass the wrong key to item("id","key"). When you pass undefined as key of this method, it means you don't define partition key value of document which id is '1' like this screenshot.

    enter image description here

    I guess your document which id is '1' has partition key value, so cosmos DB can't find the document which id is '1' and doesn't have partition key value. If so, you need to pass your partition key value to item("id","key").

    For example, I have a document like below, my code should be like this:

    const item = container.item("1", "dog");
    console.log("Read item '" + item.id + "'");
    const { resource: readDoc } = await item.read();
    console.log("item with id found: '", readDoc);
    

    enter image description here