0

I have a data structure, like so

{
  _id: '',
  name: 'A',
  financialReports: {
    monthlyBill: 20,
    monthlyBillReports: [
      {
        month: 'JAN',
        isPaid: true
      },
      {
        month: 'FEB',
        isPaid: false
      },
      {
        month: 'MAR',
        isPaid: false
      },
      {
        month: 'APR',
        isPaid: false
      },
      ...
    ]
  }
},
...

How should I dynamically update financialReports.monthlyBillReports[i].isPaid to true? I got array of data that indicate to month field in Database from front-end ['FEB', 'APR'], But I am not sure if I could iterate over the array and make update query to Database.

1 Answer 1

1

you can do a loop something like:

let yourArray = ['FEB', 'APR'] // just mocking the array

yourArray.forEach((mo)=>{
      collectionName.findOneAndUpdate( 
             {_id: 'document id goes here'},
             { '$set': {'financialReports.monthlyBillReports.$[frFilter].isPaid': true}},
             { arrayFilters: [ {frFilter.month: mo} ], multi: true}
          ).then(
                //do whatever you need here
          )
    })  

or in a more straight forward manner:

collectionName.findOneAndUpdate( 
                 {_id: 'document id goes here'},
                 { '$set': {'financialReports.monthlyBillReports.$[frFilter].isPaid': true}},
                 {arrayFilters: [ {frFilter.month: {$in: yourArray} } ], multi: true}
              ).then(
                    //do whatever you need here
              )
Sign up to request clarification or add additional context in comments.

5 Comments

It works but instead of changing isPaid to true It writes a new isPaid: true So i got two isPaid which have value false and true respectively, How to fix this ? thank you for your help by the way
sorry, ive edited the code. there was a space between $[frFilter]. and isPaid, ive removed that. just make sure remove the other isPaid fields first, before running it again
and oh, should be financialReports.monthlyBillReports.$[frFilter] instead
why you dont go with updateMany and filter it like this arrayFilters: [ {frFilter.month: { $in: ["FEB", "APR"] }} ] so you dont need to go with a forEach
that will work too arrayFilters: [ {frFilter.month: {$in: yourArray} } ], i think there is no need for updateMany as it only affects one document

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.