Skip to content
Advertisement

update two layer nested object based on the id

I have this structure in my Mother Model (this is a fixed structure and I just push cards or update them on these 3 array levels):

JavaScript

The Objects inside cards.advanced array above are like:

JavaScript

Assuming I have access to Mother model like this:

JavaScript

How can we update a card object based on its id and the level it belongs to and replace the whole card object with newCard ?

JavaScript

I have tried this with no luck:

JavaScript

I have tried this one too but it doesn’t change anything in the Model:

JavaScript

Advertisement

Answer

You can actually sort your problem out with the update method, but you have to do it in a different way if you are using MongoDB 4.2 or later. The second parameter can be the $set operation you want to perform or an aggregation pipeline. Using the later you have more liberty shaping the data. This is the way you can solve your problem, I will breakdown after:

JavaScript

First with use the update method passing three parameters:

  • Filter query
  • Aggregation pipeline
  • Options. Here I just used new: true to return the updated document and make it easier to test.

This is the structure:

JavaScript

Inside the pipeline we only need one stage, the $set to replace the property advanced with an array we will create.

JavaScript

We first map the advanced array to be able to map the nested cards array after:

JavaScript

We use the variable we declared on the first map and which contains the advanced array current item being mapped ( adv ) to access and map the nested “cards” array ( $$adv.cards ):

JavaScript

Lastly we check if the current card id is equal to the id being searched $eq: [ "$$advcard.id", "main-2-1" ] and return the new card if it matches or the current card:

JavaScript

Here is a working example of what is described: https://mongoplayground.net/p/xivZGNeD8ng

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement