"Upon deletion, Cosmos DB entity was not found, although it was confirmed to exist and could be retrieved

Every time I attempt to remove an Item using its ID, I encounter an entity not found error, even though the Item is present in the database and can be retrieved using SQL format.

I'm unable to pinpoint where the issue lies in my code because when I retrieve an item by its ID, it exists. However, attempts to delete it fail.

Here is the code for fetching:

async getAsset(assetId: string): Promise<Asset> {
    const assetsDb = await getDbClient(cosmoDBContainers.assets);
    const response = await assetsDb.items
      .query<Asset>({
        query: `SELECT * FROM ${cosmoDBContainers.assets} A 
                WHERE A.id = @id`,
        parameters: [{ name: "@id", value: assetId }],
      }).fetchAll();
    return response.resources.map(x => new Asset(
      x.id,
      x.orgId,
      x.assetType,
      x.title,
      x.createdAt,
      x.lastUpdate,
      x.fileStorageId,
    ))[0];
} // item successfully retrieved

This is the deletion code (note that I invoke the getAsset function):

async removeAsset(assetId: string): Promise<void> {
    const assetsDb = await getDbClient(cosmoDBContainers.assets);

    const asset = await this.getAsset(assetId); // verifying IDs match, which they do
    const item = assetsDb.item(asset.Id); // this line executes correctly
    await item.delete(); // error occurs here
  }

The partition key in CosmosDB is "/id". I have attempted adding it when calling assetsDb.item(asset.Id, "/id"), but the same "not found" error persists.

Here is the full error message:

 Error: Entity with the specified id does not exist in the system.

I've tested several solutions from other Stack Overflow answers, but none seem to resolve the issue. It appears to be a problem on my end, and I am currently at a loss. Any insights would be greatly appreciated.

I am working with TypeScript and "@azure/cosmos": "^3.11.0"

Thank you.

Answer №1

Here are the necessary changes to your code:

const item = assetsDb.item(asset.Id);
await item.delete();

Replace it with:

const item = assetsDb.item(asset.Id, asset.Id);//assuming your partition key value is same as document id.
await item.delete();

Your delete operation should now function correctly.

The issues can be summarized as follows:

  1. In the line
    const item = assetsDb.item(asset.Id);
    , you did not specify the partition key value of the document. This caused the SDK to use the default partition key value, resulting in an "item not found" error.
  2. When attempting
    assetsDb.item(asset.Id, "/id")
    , you mistakenly used the partition key attribute name instead of its value. Consequently, Cosmos DB searched for a matching id within the logical partition "/id," leading to the error.

With

const item = assetsDb.item(asset.Id, asset.Id);
, both the item's id and partition key value are accurately provided to Azure Cosmos DB.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of TypeScript's dual generic typing feature?

defineListenerShape< EventName extends string, EventData extends { [key in EventName]: unknown; } > = <E extends EventName>(data: EventData[E]) => void; enum EventName { Click = 'click', Hover = 'hover' ...

Convert an array with three dimensions into a two-dimensional array that includes tuples with two immutable string values

Consider the array below with multiple dimensions: type ParsedLine = [string, string]; type ParsedLines = [ParsedLine, ParsedLine] const myArray: (ParsedLine | ParsedLines)[] = [ ['something', 'somethingElse'], [['foo', & ...

Limit the number of years shown in the dropdown menu to verify that the user is at least 18 years old

I have a dropdown for selecting the year on my form, where the user will enter their date of birth. My goal is to determine how many years I should display in the dropdown to ensure the person is at least 18 years old. Currently, I am calculating this by ...

TS2365: The '!== 'operator is not compatible with the types ""("" and "")""

function myFunction(identifier: string) { identifier = "("; }; let identifier: string = ")"; if (identifier !== '(') throw "Expected '(' in function"; myFunction(identifier); if (identifier !== ')') throw "Expected &a ...

Angular 2 components not properly handling two-way binding errors

Exploring how to achieve two-way binding in Angular 2, I am currently working with the following parent component setup: app.component.html: <child [(text)]="childText" (textChanged)="textChanged($event)"></child> <span>{{childText}}< ...

Combining files/namespaces/modules in Typescript: How to do it?

Even though I believe the solution may be simple, understanding how to merge enums across multiple files is eluding me when reading through the documentation. // a.ts enum Color{ RED, BLUE } // b.ts enum Day{ MONDAY, TUESDAY } // c ...

Having trouble importing PouchDB into an Angular 5.2.0 project

Struggling with integrating PouchDB into my Angular project, I've experimented with various import methods : import PouchDB from 'pouchdb'; import * as PouchDB from 'pouchdb'; In my service, I'm utilizing it like this : dat ...

When the component I created for dark mode is clicked, the colors in react-tsparticles change dynamically

I am looking to modify the theme of the react-tsparticle component function Particle() { const particlesInit = (main) => {}; const particlesLoaded = (container) => { <DarkMode />; container.loadTheme("dark&q ...

Retrieve and showcase data using Ionic 2's local storage functionality

Hi, I'm having trouble accessing my data in local storage. Every time I try, it gives me an error. I need assistance with displaying my data at home. Thank you for your help :) Error: Typescript Error Argument of type 'Promise' is not assi ...

Create a placeholder class for the Form Builder group component within an Angular application

Currently, I am in the process of creating numerous new forms. For instance: constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ 'name': ['', Validators.required], 'email&apo ...

Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community, As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy. I currently have three pages with numerous FormGroups that overlap signif ...

Utilize TypeScript Compiler (tsc) without the need for global installation via

Currently, I am tackling a project that needs to be delivered to a group of individuals. This project is written in TypeScript, requiring them to execute the command tsc for compilation. The issue arises when I run this command following the execution of ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

Example of TypeScript Ambient Namespace Usage

The Namespaces chapter provides an example involving D3.d.ts that I find puzzling. Here is the complete example: declare namespace D3 { export interface Selectors { select: { (selector: string): Selection; (element: ...

What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with: <p [innerHTML]="aboutUs"></p> Due to t ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

Using NodeJS to retrieve data from Firestore and then transmitting it to a Google Spreadsheet

I've been comparing data from a spreadsheet with a firebase collection to find matching values and retrieve an answer. Now, I need help on how to transfer this answer to another Google spreadsheet. Although I've attempted the method below, I&apo ...

The alias for the computed column is not correctly connected to the TypeORM Entity

I am currently working on extracting data from a table in a MySQL database using TypeORM for my Express.js project. In order to retrieve the data, I am utilizing the QueryBuilder. This is the implementation I have: const result = await this.repository.cr ...

Typescript code encountering unexpected behavior with Array.includes()

Below is a snippet of TypeScript code from my NextJS application: const holeSet:any[] = []; ..... let xx = 1, yy = 2; holeSet.push({x:xx,y:yy}); xx = 3; yy = 4; holeSet.push({x:xx,y:yy}); holeSet.map((e) => { console.log("element ::"+JSON ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...