如何在loopback中保留模型上插入后获取自动ID?

问题描述:

我有一些使用looback连接器postgresql从postgresql db生成的模型。这些模型的Id列是postgresql db的自动递增整数列。如何在loopback中保留模型上插入后获取自动ID?

1)I有加在持久性模型,其中i执行简单的更新或插入(UPSERT中的一个的远程方法。

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

2)增加了一个远程钩这个远程方法之后执行。

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

3)我要在步骤(1)用新插入行的标识,在步骤中提到的远程钩(2)

我没有关于PostgreSQL的分贝很多想法。但尝试像这样

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

现在,您可以通过使用carObj.id获得ID和任何你想去的地方,你可以使用它。我希望这有助于

+0

因为它REQ(ERR,车)后,立即到远程钩子。 carobj在远程钩子中保持“未定义”。反正汽车物体本身dosent包含“身份证”。当我插入一个新的记录。我可以在插入对象时发送{“id”= null},或者根本不指定“id”键。 –

您可以访问到生成的ID在远程钩子是这样的:

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

这个表达式在我的例子中有点不同** remoteMethodOutput.records .__ data.id || context.result.records .__ data.id ** Still genId来自未定义。当我插入一个新的记录。我可以在插入对象时发送{“id”= null},或者根本不指定“id”键。 upsert上会发生什么,它会返回与我插入的对象相同的对象。如果我在插入对象时不添加键“id”,upsert返回的对象也没有“id”。如果我将“id”指定为null,它会将id返回为null。 –

+0

@GaneshMahajan你检查了'context.result.id'吗? –

+0

是的,这也是未定义的。 Idinjection在我的模型中设置为false。因为我使用我自己的ID列。这是否有所作为? –