RSA
RSA

Reputation: 1449

How to update an attribute in loopback by updateOrCreate?

I want to update an attribute by remote method but it is not working correctly, I want to post age to from app to backend and update it in the backend.

Person.testupdate = function ( id, age, cb) {
    Person.upsertWithWhere({
      where: {
        id: id
      },

        age: age,
    },
      function (err, Person) {
        cb(null, Person);
      });
  }

  Person.remoteMethod('testupdate', {
    accepts: [{
      arg: 'id',
      type: 'string'
    }
],
    returns: {
      arg: 'result',
      type: 'string'
    },
    http: {
      path: '/updateage',
      verb: 'get'
    }
  });

};

Upvotes: 1

Views: 4172

Answers (2)

Karan Raina
Karan Raina

Reputation: 600

checkout the loopback API docs at https://apidocs.strongloop.com/loopback/#persistedmodel-upsertwithwhere

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

Update or insert a model instance based on the search criteria. If there is a single instance retrieved, update the retrieved model. Creates a new model if no model instances were found. Returns an error if multiple instances are found.

here data should be an object.

Person.testupdate = function ( id, age, cb) {
    Person.upsertWithWhere({
      where: {
        id: id // or just where : { id } in shorthand
      },
      // age: age,
      {age: age}, // or just {age} in shorthand

        
    },
      function (err, Person) {
        cb(null, Person);
      });
  }

  Person.remoteMethod('testupdate', {
    accepts: [{
      arg: 'id',
      type: 'string'
    }
],
    returns: {
      arg: 'result',
      type: 'string'
    },
    http: {
      path: '/updateage',
      verb: 'get'
    }
  });

};

Also, you are returning a model instance but the return argument is string. You might wanna change that.

See if it works. Rest seems okay to me

Upvotes: 2

can you try this code, first you need to find the record by the id parameter, update the age field and then save it.

Take a look of the accepts property in the remoteMethod definition you need to add the age param as well.

Person.testupdate = function (id, age, cb){
    Person.findById(id, function (err, person){

        person.age = age;

        return person.save(function (err, personSaved){
            cb(null, personSaved);
        })
    })
}
Person.remoteMethod('testupdate', {
    accepts: [{
            arg: 'id',
            type: 'string',
            required: true
        },
        {
            arg: 'age',
            type: 'number',
            required: true
        }
    ],
    returns: {
        arg: 'result',
        type: 'object'
    },
    http: {
      path: '/updateage',
      verb: 'POST'
    }
})

Upvotes: 1

Related Questions