4

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);
})
2
  • Please clarify what you mean by a sequelize array - A column of the array type, an array of instances? Commented Jun 6, 2016 at 7:16
  • A column of the array type Commented Jun 9, 2016 at 3:50

2 Answers 2

5

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
});
Sign up to request clarification or add additional context in comments.

Comments

2

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){

    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.