Tuesday, 24 January 2023

Object not getting updated when values are 0 in bulk operation

I'm parsing a CSV file and updating a MongoDB database based on its values. I just noticed that if the subelements of an object are zero or null the values are not getting updated. How can I solve this?

MongoDB values pre-execution:

{
...
  "AC": {
    "AC1": 3100,
    "AC2": 3100,
    "AC3": 5000,
    "AC4": 3100,
    "AC5": 3100,
    "AC6": 5000
  }
...
}

Now, the excel has been updated to the following values, so I try to update it in the MongoDB database.

    "AC1": 3100,
    "AC2": 3100,
    "AC3": 5000,
    "AC4": 0,
    "AC5": 0,
    "AC6": 0

But, after the bulk operation, I get nModified: 0 and no changes.

If the values are different than 0 (e.g. 1), it works and the values are updated successfully.

The code is the following:

    // ... (Adding other subobjects to set)
    // Subobject AC

    if (element.acs) {
        let i = 1;
        for (let ac in element.acs) {
            console.log("AC.AC" + i, element.acs[ac]);
            if (element.acs[ac]) set["AC.AC" + i] = element.acs[ac];
            i++;
        }
    }

    // Result of console.log seem good:
    // AC.AC1 3100
    // AC.AC2 3100
    // AC.AC3 5000
    // AC.AC4 0
    // AC.AC5 0
    // AC.AC6 0

    bulk
        .find({ id: element.id })
        .upsert()
        .update({ $set: set });

    // After this, no update is done. Values in BBDD for that object:
    // AC.AC1 3100
    // AC.AC2 3100
    // AC.AC3 5000
    // AC.AC4 3100
    // AC.AC5 3100
    // AC.AC6 5000


from Object not getting updated when values are 0 in bulk operation

No comments:

Post a Comment