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

insert or update(upsert) in loopback application

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

我的 table 如下所示:

userid  bbid saved  id(PK)
  1      5    1000   1

所以下次 if(bbid = 5) 它应该更新上面的行,如果 bbid =5 不存在它应该插入上面 table.

我尝试了以下方法:

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

编辑组合 ID:

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

还查看了 Loopback 文档,上面写着

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

您可以使用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);  
    });

loopback 中有两种方法,一种是简单的upsert,第二种是upsertWithWhere.To 根据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){});

这将解决您的问题。

注意:这只会更新单个 instance.If 返回多个实例,条件结果会抛出错误。