Yamoshi Wolverine
Yamoshi Wolverine

Reputation: 549

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?

Upvotes: 2

Views: 1843

Answers (1)

ALPHA
ALPHA

Reputation: 1155

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
        }
    }
    };

Upvotes: 1

Related Questions