Loopback Find then update attribute or delete by id

10,408

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
    })
 })
Share:
10,408
Mark Ryan Orosa
Author by

Mark Ryan Orosa

Web developer since 2008. Mostly I focus on developing web systems for private companies, in various industries. As a PHP developer, I sure to make use of frameworks such as Yii2 or Laravel 5, so I could focus less on PHP but more on developing or designing the system itself, ensuring a user friendly UI. Recently been shifting to REST API, and been trying out Loopback.io, with MongoDB.

Updated on June 24, 2022

Comments

  • Mark Ryan Orosa
    Mark Ryan Orosa almost 2 years

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