0

I'm building a project on sails (0.10.0-rc5) for a few days and in a few cases i need to update multiple entries at once with the same data so I made something up ...

Servers.find({owner_id: anonymous_user.id}).exec(function(error, servers) {

  catches.error(error);
  queries.save_each(servers, {owner_id: user.id});

});

The interesting part is queries.save_each() which I created ...

/**
 * Save each ActiveRecord objects with the desired attributes
 * @param  {object} objects ActiveRecord object (e.g. servers, users)
 * @param  {object} updates datas to update
 * @return {void}
 */
save_each  = function(objects, updates) {

// For each object we will update the wanted datas
for (var n in objects) {

    objects[n] = variables.inject(objects[n], updates);
    objects[n].save(function(error) { 

        catches.error(error);

     });

}

}

Basically, it's checking each entry and updating it from the new datas with save(). It works fine, but i'm wondering if there's nothing already done in waterline to do so ; I didn't find anything, but i'm quite beginner in sails maybe i missed something !

Any idea ?

Laurent
  • 2,284
  • 2
  • 21
  • 41
  • 1
    Have you actually looked at the Sails docs, particularly for [.update()](https://github.com/balderdashy/sails-docs/blob/master/reference/ModelMethods.md#update-criteria--criteria--callback-)? – sgress454 Apr 26 '14 at 22:30
  • some difficulties to check the doc and that's how you make a whole useless system ! thanks ;) – Laurent Apr 27 '14 at 03:34

2 Answers2

7

For the record, to update records in Sails, use the update method:

Model.update(criteria, data).exec(callback);

for example:

Servers.update({owner_id: anonymous_user.id}, {owner_id: user.id})
       .exec(function(err, updatedServers) {
                 // do something
             });

Documentation for update is on the here.

Muntasim
  • 6,689
  • 3
  • 46
  • 69
sgress454
  • 24,870
  • 4
  • 74
  • 92
  • 1
    It seems like the docs are pretty empty. Where did you find this? – theblang Sep 10 '14 at 03:26
  • Hi Mattblang, The docs used to be awesome but they changed since v0.10, in the new docs click on the three items at the top - Anatomy reference and concepts. – Ryan Knell Dec 15 '14 at 07:15
  • But how do we retain existing data while updating? I don't want to override them. – coder9 Jul 28 '15 at 08:45
  • The `update` method will only overwrite the data supplied as the second argument. Any fields you don't specify in that argument will remain untouched. – sgress454 Jul 29 '15 at 02:57
0

This worked for me:

Here we have a set of Photos, which we want to update.

var photos= [1,2,5]; //update the status of these 3 photos at once!
var values = {status:"accepted"};

Photo.update(photos,values).exec(function afterwards(err, updated){

       if (err) {
                res.json(err)
                return;
       }
       res.json({err:"Everything worked"})
 });
Suisse
  • 3,467
  • 5
  • 36
  • 59