1

Using node.js (v0.10.12) and sequelize (2.0.0-dev9), I am wanting to update attributes within an existing database table. From anther SO discussion I am able to update only one record at a time. I encapsulated the call in a for loop but that updated the same record throughout the for loop.

Could someone help me modify this code to update all records that match the search requirements? Below is my code:

global.db.Task.find({ where: {"Cd": "match"} && {"Desc": null}
                                      }).on('success', function(task) {                                 
                                          if (task) { // if the record exists in the db                                                               
                                              task.updateAttributes({
                                                  Desc: "New Upate"
                                              }).success(function() {});
                                              }
                                      })
Community
  • 1
  • 1
Val
  • 1,260
  • 5
  • 23
  • 39

1 Answers1

5

According to the docs you need to do a BulkCreate: (Not tested)

global.db.Task.update(
    {Desc: 'New Upate'},       //set attribute 
    {cd: 'match', Desc: null}  //where criteria 
  ).success(function(affectedRows) { ... });
dibi
  • 3,257
  • 4
  • 24
  • 31
  • Hey Daniel, your guidance is correct. However, your code has an extra }) at the end. If you can make this correction I will be able to mark your answer correct. The docs provide an example of adding and updating multiple instances, in bulk, during each call with bulkCreate and update methods. From testing, I further reduced the code so there is ONLY bulk updates. Just remove the Model.bulkCreate method from the example you provided in the Sequelize docs. – Val Jun 29 '14 at 21:43
  • ahh I see did not read the docs completly. Just updated my answer. thank you. – dibi Jun 29 '14 at 21:52
  • With your updated comment I figured out the conditional AND statement. Thank you for the update. – Val Jun 29 '14 at 22:14
  • Hey Daniel. I just noticed the "," within your update call. There are no comma's at the end of the } for the set attribute and where criteria. You can see this in the link to the sequelize docs you provided. Please update. – Val Jun 30 '14 at 19:10