7

Been trying to find samples usage for some of the static methods for a persistedModel in Loopback.

https://apidocs.strongloop.com/loopback/#persistedmodel-prototype-updateattribute

it just says:

persistedModel.updateAttributes(data, callback)

But how you I choose the which record I want to update? this is not working for me.

var order = Order.setId('whateverrecordId');
order.updateAttributes({name:'new name'},callback)

Loving loopback.. but their doc, sucks.. :(

Mark Ryan Orosa
  • 847
  • 1
  • 6
  • 21

2 Answers2

3

1- What you did was right but i do not advise this method it's used for instance methods and generally to update fields like date for all the collection that you have so you don't need an id for it.

But you can try to make an array containing data to update containing also the ids and then make a comparison to fill in data for the ids that you have. (in #dosomething)

order.find().then(function(orders) {

          orders.forEach(function(element) {

            order.setId(element.id); 
            #DoSomething
            order.updateAttribute({new: data}, function(err, instance) {

              console.log(instance);
            })
          });
        })

2- You can use updateAll to update one or many attribute.

PersistedModel.updateAll([where], data, callback)

var Updates = [{id : 1, name: name1}, ...]
Updates.forEach(function(element) {
order.updateAll({id : element.id}, {name :element.name}, function(err, count) {
      if (err) {
        console.error(err);
      }
      console.log(count); // number of data updated
    })
 })
Anouar Kacem
  • 635
  • 10
  • 24
  • 1
    Actually, updateAll is used to update more than one **row**, not more than one **attribute**. To update more than one attribute, use **updateAttributes**, and to update only one attribute, use **updateAttribute**. [source link](https://loopback.io/doc/en/lb3/Creating-updating-and-deleting-data.html) – Vinícius Queiroz Sep 18 '18 at 17:26
3

You can use those on event listener like AfterSave

example:

Model.observe('after save', function(ctx, next) {
   ctx.instance.updateAttribute(fieldname:'new value');
   next();
});