0

So the problem is this. I'm reading some values from an API and I'm doing the initial insert with each new subscription. However, once I fetch the daily records, I want to match the dates of the already written object within the array so I can replace its values. Currently, all it does is inserting the object values again. I was hoping for an overwrite.

// API logic (within a forEach loop)
//   ....

// if there's a new value the current day
if (present_date == item.date){
   // update existent via the date
   User.update(
     { "object_array" : { "$elemMatch": { "date": present_date } }},
     { $set: { "object_array.$.value": item.value } },
   );

} else { 
  // push new values with new dates
  doc.object_array.push({ 
     value: (item.value) ? item.value * .15 : 0,
     date: item.date
  });
} 
...
// outside loop
doc.save();

Any insight? I must be missing something.

incalite
  • 3,077
  • 3
  • 26
  • 32
  • 1
    *"...I was hoping for an overwrite."* - This is exactly what the `$set` with the positional operator is doing. Perhaps the `if (present_date == item.date)` part might be your problem. We don't know since you did not include that in the question. But **updating matched array elements** works exactly the same as the day it was introduced. – Neil Lunn Nov 08 '19 at 11:47
  • 1
    I might also note `doc.save()` and the comment of *"outside loop"* generally suggests you are missing quite a few concepts here. The `update()` is actually **changing the document**. There is no need to do *"another thing"* to alter the document. Also these are asynchronous operations, and none of your code shows you waiting for their completion, and certainly not "within a loop". – Neil Lunn Nov 08 '19 at 11:50
  • Probably the condition might be faulty, however It would be preferable to cut back on your assumptions and the butchered commentary, because it's not helping. I haven't shared the rest of the code. If I'm pushing multiple elements within the loop, providing none of the if clause trues fired, how will I save the changes to the document afterwards? Can't perform a save with each iteration. thanks – incalite Nov 08 '19 at 12:02

0 Answers0