Jarvan Jarvencio
Jarvan Jarvencio

Reputation: 809

How to delete items of array based on object id list in mongoose?

I'm stuck with this and I thought you could help me somehow, from the frontend it arives me a list of numbers which contains the ids of the object to be removed, for instance :

{
  "user":"TEST",
  "conditionsToDelete":[1586513509594,1586513519698]
}

And my documents on mongo look like:

enter image description here

As you see there is a property named id on the document > conditionConfig > id

So this list which comes me from the front has this id's which I have to use in order to filter and delete the matching objects.

How I can do it? I've been trying something like the following:

let resBusqueda = await this.conditionModel.find({ user: conditionsPack.user });
    resBusqueda.forEach(condicionPack => {
      let condicionesFiltradas = [];

      condicionPack.conditionConfig.forEach(condicion => {
        let idAnalizadoActualSubcondicion = conditionsPack.conditionsToDelete.indexOf(condicion.id);
        if (idAnalizadoActualSubcondicion == -1) {
          condicionesFiltradas.push(condicion);
        }
      });
      condicionPack.conditionConfig = condicionesFiltradas;
      condicionesFiltradas = [];
    });

I receive the Document and make some changes on it but how can I save them?

Ty in advance

Upvotes: 0

Views: 295

Answers (1)

arianpress
arianpress

Reputation: 475

there is a good example in here. but this might be good enough for you:

db.YourModel.update(
    { }, // conditions that specify your user instance
    { $pull: { firstArray: { $in: arrayOfObjectIds }, secondArray: "single ID" } },
    { multi: true }
)

I brought you example for single element removal and for your case, array of elements to be removed.

Upvotes: 1

Related Questions