Search code examples
node.jsfor-looploopbackjsupdate-attributes

How to update multiple objects in loopback?


can somebody help me to update some multiple object in loopback but i don't have any idea on how to do it..

this is what i tried...

Bond.ParseBondQoutesheet = (data, cb) => { //eslint-disable-line
    //// now update multiple
    for (let i = 0; i <= data.length; i = +i) {
        const filter = {
            where: { id: data[i].id },
        };
        Bond.findOne(filter, (err, newdata) => {
            if (!err) {
                newdata.updateAttributes(data[i], function (err, updated) {
                    if (!err) {
                        if (data.length === i) {
                            console.log('updated success')
                            cb(null, updated);
                        }
                    } else {
                        console.log('err')
                        console.log(err)
                        cb(err, null);
                    }
                })
            } else {
                cb(err, null);
            }
        });
    }
};

is this correct?


Solution

  • You can run that but because of JavaScript's async nature it will behave unexpectedly what you can do in order to solve this would be to loop it using recursive method like this

    Bond.ParseBondQoutesheet = (data, cb) => { //eslint-disable-line
        //// now update multiple
        let data = data;
        updateAllSync(0);
        function updateAllSync(i) {
            if (i < data.length) {
                const filter = {
                    where: { id: data[i].id },
                };
    
                Bond.findOne(filter, (err, newdata) => {
                    if (!err) {
                        newdata.updateAttributes(data[i], function (err, updated) {
                            if (!err) {
                                if (data.length === i) {
                                    console.log('updated success')
                                    updateAllSync(i+1);
                                }
                            } else {
                                console.log('err')
                                console.log(err)
                                cb(err, null);
                            }
                        })
                    } else {
                        cb(err, null);
                    }
                });
            }else{
                cb(null,i); // finished updating all docs sync
            }
        }
        };