简体   繁体   中英

How to update array object to mongoDB

I was trying to import CSV and save data into MongoDB, the import CSV should have include function where the CSV data will be automatically updated to MongoDB if there is an existing document with different values. I did the part where non-existing document has been inserted to MongoDB, but not the update function. The code below is the code that I've written so far.

Bank.csvAdd = function (csvData) {
if (csvData.length > 0) {
    let id;
    let validate;
    let arr = [];
    let csvaddArray = [], aux = {}, csvUpdateArray = [];


    for (let i = 0; i < csvData.length; ++i) {
        validate = false;
        for (let b of Object.values(Bank.byId)) {
            console.log("B.id :", Bank.byId);
            console.log("B.name :", b);
            if (csvData[i].name === b._name) {
                validate = true;
                break;
            }
            if (csvData[i].code === b._code) {
                validate = true;
                break;
            }
        }
        if (validate === false) {
            id = require.main.Nebula.generateId(6);
            if (!Bank.byId[id]) {
                aux = {
                    id: id,
                    name: csvData[i].name,
                    code: csvData[i].code
                }
                csvaddArray.push(aux);
            }
        }
        if (validate == true) {
            csvUpdateArray.push(csvData[i]);
        }
    }


    console.log("CSV data arr: ", csvaddArray);
    let col = require.main.Nebula.i.db.collection("bank");

    for (let i = 0; i < csvUpdateArray.length; ++i) {
        let col = require.main.Nebula.i.db.collection("bank");
        col.update({ id: csvUpdateArray[i].id }, csvUpdateArray[i], {upsert: true, multi: true });
    }


    col.insertMany(csvaddArray, function (err, res) {
        arr = csvaddArray.map(
            obj => {
                return {
                    "id": obj.id,
                    "_name": obj.name,
                    "_code": obj.code
                }
            }
        );

        for (let i = 0; i < arr.length; ++i) {
            Bank.byId[arr[i].id] = arr[i];
        }

        if (err) {
            throw {
                status: 2,
                data: err
            }
        };

    });
    throw {
        status: 1,
        data: arr
    }
}
else {
    throw {
        status: 3,
        data: Error

    };
}}

My csvaddArray is look like this (same as csvUpdateArray)

[ { id: 'qZp2mK', name: 'Maybank Berhad', code: 'MBB' }, { id: 'OBs79c', name: 'Standard Chartered Malaysia', code: 'SCM' } ]

My Bank.byId is looks like this (it used for loop and saved all mongoDB documents as local)

{ '7b3wJ9': Bank { id: '7b3wJ9', _name: 'Maybank Berhad', _code: 'MBB' },'2OS4Y4': Bank { id: '2OS4Y4', _name: 'Standard Chartered Malaysia', _code: 'SCM' }}

In MongoDB compass it looks like this sample documents in mongoDB

first try to code the functionality as short as possible to improve execution speed.

     for (let i = 0; i < csvUpdateArray.length; ++i) {
          let col = require.main.Nebula.i.db.collection("bank");
          col.update({id:csvUpdateArray[i].id},{$set: 
          {name:csvUpdateArray[i].name,code:csvUpdateArray[i].code}}, 
           {upsert:true,multi:true},function(err,updated)
             {

             })
          }

In the above code will do insert and update by using the keyword {upsert:true} , if id is alredy exist it will update and if not this upsert key will insert the data as new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM