Laurent Laurent - 4 months ago 27
Node.js Question

Multiple model updates in sails waterline

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 ?

Answer

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.