Loopback Find then update attribute or delete by id
Asked Answered
M

2

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

Mockery answered 3/10, 2017 at 0:1 Comment(1)
Shouldn't it be order.updateAttributes({name:'new name'},callback)?Avestan
R
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();
});
Racquelracquet answered 27/10, 2017 at 7:22 Comment(0)
S
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
    })
 })
Sacramental answered 3/10, 2017 at 7:0 Comment(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 linkOssian
R
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();
});
Racquelracquet answered 27/10, 2017 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.