问题
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 ?
回答1:
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.
回答2:
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"})
});
来源:https://stackoverflow.com/questions/23312002/multiple-model-updates-in-sails-waterline