在loopback应用程序中插入或更新(upsert)

时间:2016-07-01 06:26:53

标签: node.js loopbackjs upsert

我使用Loopback框架开发了一个API,因为我必须insert or update到表。

我的表格如下:

userid  bbid saved  id(PK)
  1      5    1000   1

所以当下次if(bbid = 5)时它应该更新上面的行,如果没有bbid = 5那么它应该插入到上面的表中。

我尝试了以下内容:

app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
              ,function(err, res){
});

编辑COMPOSITE ID:

app.models.modelname.upsert({bbid:vvvv.bbid, userid:1,saved:amountSaved},function(err, res){
});

它也通过Loopback doc说了

    upsert - checks if the instance (record) exists, based on the designated 
ID property, which must have a unique value; if the instance already exists, 
the method updates that instance.  Otherwise, it inserts a new instance.

但在我的情况下,它应检查bbid not id

但它每次插入。请分享您的想法。提前致谢

编辑UPSERT:

我的流程如下:

Fetch from table1 and loop that response and calculate the saved and upsert it into another table(table2 (this is where upsert should happen)). Also the fetching from table1 will happen frequently so suppose consider if is happens 2nd time it should update the already present bbid..

2 个答案:

答案 0 :(得分:6)

您可以使用findOrCreate方法,如下所示:

app.models.modelname({where: {bbid:bb.id} }, {bbid:bb.id, saved: Saved, userid:1}, function(err, instance) {
    if (err){
        cb(null, err);
    }
        cb(null, instance);  
    });

答案 1 :(得分:1)

loopback中有两种方法,一种是简单upsert,另一种是upsertWithWhere。要根据where条件插入或更新你必须使用upsertWithWhere方法upsert只插入数据。 你正在使用

app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

改为使用

app.models.modelname.upsertWithWhere({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

这将解决您的问题。

注意:这只会更新单个实例。如果在条件结果的地方返回多个实例,则会抛出错误。

相关问题