0

I try to make a cronjob which checks last updates of files.

But when a new Object is to be pushed in the array of file information the array is complete overwritten. Could someone give a hint, please? Tried also with "push(...value)"

const cron = require('node-cron');

let openCalculationFiles = [{}];

module.exports = {
    cronjobCalculationUsage: () => {

      cron.schedule('30,0 * * * * *', async() => {
        ....
      });
    },
    upsertOpenCalculation: (projectId) => {

      console.log(openCalculationFiles);
      const openCalculation = openCalculationFiles.filter(element => element.projectId = projectId)[0];

      if (openCalculation) { // This works
        openCalculation.lastUpdate = new Date().getTime();
      } else {


        const newOpenCalculation = {
          "projectId": projectId,
          "lastUpdate": new Date().getTime()
        };


        openCalculationFiles.push(newOpenCalculation); // This makes complete new Array, last one wins
      }

      console.log(openCalculationFiles);
    }
Barmar
  • 741,623
  • 53
  • 500
  • 612
Buzz
  • 315
  • 6
  • 18
  • How do you know that it is being overwritten? – Shmack Nov 21 '22 at 21:02
  • `if (openCalculation)` will always succeed. `filter()` returns an array, and all arrays are truthy (this is not like Python or PHP, where empty lists/arrays are falsey). – Barmar Nov 21 '22 at 21:04
  • `openCalculation.lastUpdate` doesn't seem correct. `openCalculation` is an array. You should be assigning to properties of the array elements, not the array itself. – Barmar Nov 21 '22 at 21:05
  • You should probably be using `find()` instead of `filter()`. It returns the element that matches the criteria, not an array of all the matching elements. – Barmar Nov 21 '22 at 21:06
  • 1
    What's the purpose of the empty object in the initial value of `openCalculationFiles`: `[{}]`? It should probably just be `[]` – Barmar Nov 21 '22 at 21:06
  • @Barmar. Thx. The {} inside the array was just the last try since I stucked in solution finding. Since I take [0] in filter, openCalculation is not an array but the object itself. But better I should use find(), you are right – Buzz Nov 21 '22 at 21:20
  • see: [What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)](https://stackoverflow.com/questions/11871616/what-is-the-difference-between-the-and-operators-and-what-is-si) – pilchard Nov 21 '22 at 21:30

1 Answers1

0

Your filter is not filtering but overwriting:

openCalculationFiles.filter(element => element.projectId = projectId)[0];

should be

openCalculationFiles.filter(element => element.projectId === projectId)[0];
spedy
  • 2,200
  • 25
  • 26