Loopback Find then update attribute or delete by id

Mark Ryan Orosa picture Mark Ryan Orosa · Oct 3, 2017 · Viewed 8.9k times · Source

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.. :(

Answer

Anouar Kacem picture Anouar Kacem · Oct 3, 2017

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
    })
 })