'Mongoose findOne() in a for loop using set if extist or put if doesn't

In mongoose when i call find() function and update inside the find finction , the function iterate but data is not inserted into subarray it is inserted into root array.

this is my code

for (let k in listMed) {
    insertUpdate(listMed[k]);
}

Function

function insertUpdate(med) {
StockDB.findOne({ Medicine_name: med.Medicine_name }, function (err, element) {
    if (err) {
        console.log(err);
    }
    else {
        console.log(element);
        if (element != null) {
            element.MRP = med.MRP;
            element.Rate = (parseFloat(med.MRP) / parseFloat(med.PerCount));
            element.Items.push({
                Batch_no: med.Batch_no,
                Exp_date: med.ExpDate,
                Quantity: med.PerCount
            });
            element.save();
        }
        else {
            StockDB.insertMany({
                Medicine_name: med.Medicine_name,
                MRP: med.MRP,
                Rate: (parseFloat(med.MRP) / parseFloat(med.PerCount)),
                Items: [{
                    Batch_no: med.Batch_no,
                    Exp_date: med.ExpDate,
                    Quantity: med.PerCount
                }]
            });
            
        }
    }
});}

I want to store like this

[
    {
        Medicine_name: "Rantac 150",
        Price : "30",
        Items : [
                   {
                       Batch_no : b123,
                       Expiry_date : 22-02-2028,
                   }
                   
                   {
                       Batch_no : b113,
                       Expiry_date : 12-05-2027,
                   }

                   {
                       Batch_no : b153,
                       Expiry_date : 20-01-2024,
                   }
                ]
     }
]

But it is srore the data like this

[
    {
        Medicine_name: "Rantac 150",
        Price : "30",
        Items : [
                   {
                       Batch_no : b123,
                       Expiry_date : 22-02-2028,
                   }
                ]
     }
     
     {
        Medicine_name: "Rantac 150",
        Price : "30",
        Items : [
                   {
                       Batch_no : b113,
                       Expiry_date : 12-05-2027,
                   }
                ]
     }
     
     {
        Medicine_name: "Rantac 150",
        Price : "30",
        Items : [
                   {
                       Batch_no : b153,
                       Expiry_date : 20-01-2024,
                   }
                ]
     }
]

object is not push into the items array , it repeatedliy call insert function but 1st time when inserted element will be not null but it is still null



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source