mrain
mrain

Reputation: 53

Sequelize save() issue

Using Sequelize with NodeJS I have found an issue with the .save() method on a model.

Assume a database table with entries such as:

{ id : 1, name : "mary", enteredCompetition : 1, won : 0 }
{ id : 2, name : "mark", enteredCompetition : 1, won : 0 }
{ id : 3, name : "maya", enteredCompetition : 1, won : 0 }
{ id : 4, name : "maci", enteredCompetition : 0, won : 0 }

I retrieve one user that has entered the competition, and set this user as having won the prize:

User.findOne( { where : { enteredCompetition : 1 } } )
    .then( function( user ) {
        user.won = 1;
        user.save().then( function() {
            // done
        } );
    } );

The issue is that this code then proceeds to update all of the users in the database that have "enteredCompetition" set to 1.

I assume this has something to do with options of the model object that is returned from the findOne method. The whereCollection is set to { enteredCompetition: 1 }, therefore I assume when save() is called on it, it uses those where conditions in the update sql:

UPDATE `users` SET `won`=1,`updatedAt`='2015-08-19 09:59:27' WHERE `enteredCompetition` = 1

My question: is this expected behavior? I personally assumed that it would only update the record it originally pulled from the database, but perhaps I am missing a method that achieves this?

My current solution is to simply call findOne again with the id of the object that the original query returned, then call save() on this.

Upvotes: 5

Views: 7391

Answers (2)

Joshua F
Joshua F

Reputation: 908

What version of Sequelize are you using? I just ran a simple test with 3.5.1 and it's working as you'd expect.

Starting table:

+----+-------------+--------+
| id |  username   |  type  |
+----+-------------+--------+
|  1 | joshua f    | NORMAL |
|  2 | joshua f jr | NORMAL |
+----+-------------+--------+

db.user.findOne({
  where: {
    type: 'NORMAL'
  }
}).then(function(instance) {
  instance.type = 'IRONMAN';
  instance.save().then(function() {
    console.log('saved');
  });
});

Gave me the following SQL:

UPDATE `users` SET `type`='IRONMAN',`updatedAt`='2015-08-20 05:07:49' WHERE `id` = 2

And the following table

+----+-------------+---------+
| id |  username   |  type   |
+----+-------------+---------+
|  1 | joshua f    | IRONMAN |
|  2 | joshua f jr | NORMAL  |
+----+-------------+---------+

Upvotes: 2

Red Bull
Red Bull

Reputation: 11

Try to console log the user and see what it contains

Upvotes: 1

Related Questions