Function Update Massive sequelize - Node

1

Good, I am trying to make a massive update to an MSSQL database from Node using sequelize. I still do not understand very well all this of the Promises, .then () etc.

What I'm needing is a function called by POST, which receives an array of JSON objects:

[{F1:'123',F2:'a',F3:'b',F4:'Z'},
{F1:'124',F2:'a',F3:'b',F4:'Z'},
{F1:'125',F2:'a',F3:'b',F4:'Z'},
{F1:'126',F2:'a',F3:'b',F4:'Z'},]

Where F1 is the object id and F4 the field to update. Make an update on all the rows received and send a response. For a single Object, I do the following without problems:

MODEL.update(
    {
        att4: art['F4'],
    },
    {
    where:{
            att1: {$eq: art['F1']}
          }
    }).then(function(result)
    {        
        res.status(200).send();

    }).catch(function(err)
    {
        res.status(500).send(err);
    })

And everything is perfect. However, you would need to do all the updates in bulk, and then receive a response in the client, either with the number of rows affected, or the corresponding error.

I have tried putting the MODEL.update ([...]) inside a function that receives a JSON object and with a Foreach iterate the array and make a call to this function for each object, but I have not achieved what I need.

I hope you can help me. Thanks :)

    
asked by FederHico 30.05.2017 в 18:12
source

1 answer

1

Well, I researched and I found Promise.all .

I was able to do the massive update, and in the meantime I put it into a transaction to maintain the atomicity of the query. Being something like this:

app.post("/method",function(req,res)
{   
    var objs = [];
    req.body.forEach(function(art) {
        objs.push(art);
    },this);

    myModel.sequelize.transaction(function(t){
        var Promises=[];
        for(var i = 0 ; i<objs.length;i++)
        {
            var newPromise=myModel.update({
                att4:objs[i]['F4']
            },            
            {
                transaction: t,
                where:{att1: {$eq: objs[i]['F1']}}
            });
            Promises.push(newPromise);
        };
        return Promise.all(Promises).then(function(result)
        {
            res.sendStatus(200);

        }).catch(function(err){

            res.sendStatus(500).send(err);
        });
    });
});

I hope it serves someone else.

NOTE: Knowing how to use Promises is very important

    
answered by 31.05.2017 / 16:13
source