Ron Al
Ron Al

Reputation: 476

Nestjs Mongoose, How to delete array member by its _id?

The schema is like this. it's a shopping cart with items:

export interface Cart extends mongoose.Document {
  userId: string;
  total: number;
  count: number;
  status: string;
  items: [
    {
      itemId: string;
      itemName: string;
      count: number;
      price: number;
      itemTotal: number;
    },
  ];
}

if you look at the mondodb data, there is an _id to each of the members in items array. I have this _id, and i want to remove an item by that _id. The problem is, it's typescript, and _id is not part of the schema. Here is the code i use to delete an item:

const cart = await this.cartModel.findOneAndUpdate(
   { _id: dto.cartId },
   { $pull: { items: { _id: '1234567890' } } },
   { new: true },
);

Which means, in that specific cart, find the item with _id equals to 1234567890, and delete it. BUT the _id has red squiggly, as it is not part of my schema. How can I solve this?

Upvotes: 1

Views: 2130

Answers (2)

Ron Al
Ron Al

Reputation: 476

For lack of better solution, i have bypassed this issue by adding a text field called timeStamp. when an item is added to the cart, i push the current time (in ms) to that field, and that is unique enough to distinguish between entries in a shopping cart. In case you wonder, itemId is not good enough, as people can have the same item in 2 or more lines, with different details. I have added of course the new field to my schema, so typescript is not complaining ;)

Upvotes: 0

Vương Nguyễn
Vương Nguyễn

Reputation: 381

It shoulds be id not _id. Because _id is an object. But our query cannot send object to params. So, it should be a hexString.

You can change your entity _id to id by:

 @ObjectIdColumn()
 @Transform(id => id.toString())
 id: string;

So that, you can use id as hexString anywhere. Hope it helps

Upvotes: 1

Related Questions