【问题标题】:insert or update(upsert) in loopback application在环回应用程序中插入或更新(更新插入)
【发布时间】:2016-11-03 10:55:33
【问题描述】:

我使用 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) {}); 

编辑复合 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..

【问题讨论】:

  • 无法将 upsert 与另一个键一起使用。它应该是 mode.json 中定义的模型键。所以你应该获取它并更新/插入。环回中有扩展键,但我认为它不适用于 upsert
  • 最后一次尝试是的。请查看docs.strongloop.com/display/public/LB/…。为您的模型定义复合 ID,并且 upsert 可能适用于该模型
  • 你尝试过复合 id 吗?
  • 例如:"id": { "type": "string", "id": true },"bbid": { "type": "string", "id": true }
  • 您是否将id 放入发送到upsert 的数据中?

标签: node.js loopbackjs upsert


【解决方案1】:

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

【讨论】:

【解决方案2】:

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

这将解决您的问题。

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

【讨论】:

    猜你喜欢
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多