Danny McClafferty
Danny McClafferty

Reputation: 41

Update Sequelize Array

I have looked everywhere, and I have not found an easy to understand method of updating a sequelize array, like this with a normal string:

db.User.update({name:req.body.name},{where : {username:req.body.username}}).then(function(user) {

    res.json(user);
})

Upvotes: 4

Views: 10871

Answers (2)

thanh1101681
thanh1101681

Reputation: 302

Which I myself resolved as follows:

case 1: If you want to update multiple lines at the same value with different conditions

db.User.update({ name: 'name request' }, {
    where: {
        $or: [{ name: 'test 1', password: 'sasaccsa' }, {
            name: "test 2"
        }]
    }
}).then(function(user) {
    //query generate
    // UPDATE `User` SET `name`='name request' WHERE ((`name` = 'test 1' AND `password` = 'sasaccsa') OR `name` = 'test 2')
    res.json(user);
});

case 2: if you want to update multiple lines with different values for different types of reviews:

var arrayUpdate = [{
        name: 'test 1',
        id: 1
    }, {
        name: 'test 2',
        id: 2
    }, {
        name: 'test 3',
        id: 3
    }];
    sequelize.Promise.each(arrayUpdate, function(val, index) {
        return db.User.update({
            name: val.name
        },{
            where:{
                id: val.id
            }
        }).then(function(user) {
        }, function(err){

        });
    })
    .then(function(updateAll){
        //done update all
         res.json(updateAll);
    }, function(err){

    });

Upvotes: 2

Raptack
Raptack

Reputation: 371

Sequelize doesn't support bulk updates using an array, see https://github.com/sequelize/sequelize/issues/4501

You have to implement a custom function. Here is a basic example to give you an idea :

var promises = [];
userArray.forEach(function(user){
   promises.push(db.User.update({name:user.name},{where : {username:user.username}});
});
Promise.all(promises).then(function(){
    // success
}, function(err){
    // error
});

Upvotes: 5

Related Questions