How to get auto Id after upsert on a persisted model in loopback?

你离开我真会死。 提交于 2019-12-12 00:48:50

问题


I have a some models generated from postgresql db using looback-connector postgresql. Id column of these models is a auto incremented integer column of postgresql db.

1) I have a remote method added on one of persisted models, where i perform simple update or insert(upsert.

 Car.CreateOrUpdateCar = function (carobj, req)     {
    Car.upsert(Carobj, function (err, Car) {
        if (err)
            console.log(err);
        else {
            req(err, Car);
        }
    });
};

2) have added a remote hook to execute after this remote method.

       Car.afterRemote('CreateOrUpdateCar', function (context, remoteMethodOutput, next) {
//Remaining code goes here
      next();
        });

3) I want to use Id of newly inserted row in step (1), in the remote hook mentioned in step (2)


回答1:


I don't have much idea about postgresql db. But Try it like this

    var carObj;
    Car.CreateOrUpdateCar = function (carobj, req)     {
    Car.upsert(Carobj, function (err, Car) {
        if (err)
          console.log(err);
        else {
          req(err, Car); // Your Car object contains final result after upserting along with Id
          carObj = Car;
        }
     });
   };

Now you can get id by using carObj.id and you can use it where ever you want. I hope this helps




回答2:


You can access to generated id in remote hook like this :

 Car.afterRemote('CreateOrUpdateCar', function (context, remoteMethodOutput, next) {
  var genId = remoteMethodOutput.id || context.result.id;
      next();
        });


来源:https://stackoverflow.com/questions/42621993/how-to-get-auto-id-after-upsert-on-a-persisted-model-in-loopback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!