Unable to read single items from Cosmos DB

Remco 11 Reputation points
2023-05-17T22:47:09.4233333+00:00

I have a Cosmos DB database named "demo_in_container" containing a container called "resources".

When I query all items with the Javascript SDK, I see my entries.

const query = await cosmosClient.database("demo_in_container").container("resources").items.readAll().fetchAll();
console.log(query);

I have a single entry with 'wp' as id. The code gives me the following response.

FeedResponse {
  resources: [
    {
      id: 'wp',
      containerOptios: [Object],
      _rid: 'CtBUALLmYcEBAAAAAAAAAA==',
      _self: 'dbs/CtBUAA==/colls/CtBUALLmYcE=/docs/CtBUALLmYcEBAAAAAAAAAA==/',
      _etag: '"00009b81-0000-0d00-0000-646533720000"',
[       _attachments: 'attachments/',
      _ts: 1684353906
    }
  ],
  headers: { 'x-ms-request-charge': 2.27, 'x-ms-documentdb-query-metrics': {} },
  hasMoreResults: false
}

However, when I try to retrieve a single entry, I get a 404 not found response.

const query = await cosmosClient.database("demo_in_container").container("resources").item("wp").read();
console.log(query);
ItemResponse {
  resource: undefined,
  statusCode: 404,
  substatus: undefined,
  item: Item {
    container: Container {
      database: [Database],
      id: 'resources',
      clientContext: [ClientContext]
    },
    id: 'wp',
    partitionKey: [ {} ]
  }
}

I just can't figure out what I'm doing wrong. Does anyone see the problem?

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,533 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Vahid Ghafarpour 20,490 Reputation points
    2023-05-18T00:46:50.8833333+00:00

    To identify items in CosmosDB, you need to provide both ID and PartitionKey, and you missed the partition key in your sample

    Check this sample code:

    const options = {
      partitionKey: "your_partition_key_value"
    };
    
    const query = await cosmosClient
      .database("demo_in_container")
      .container("resources")
      .item("wp")
      .read(options);
    
    console.log(query);
    

  2. TP 83,711 Reputation points
    2023-05-18T19:27:21.7233333+00:00

    Hi Remco,

    In your example you need to add the partitionKey value, as below:

    const query = await cosmosClient.database("demo_in_container").container("resources").item("wp","wp").read();
    console.log(query);
    

    Please click Accept Answer if the above was useful.

    Thanks.

    -TP