【问题标题】:updating an existing item in an azure mobile service database更新 Azure 移动服务数据库中的现有项目
【发布时间】:2015-03-27 13:48:41
【问题描述】:

我有一个服务器端脚本,它试图用脚本中计算的新数据更新已经存在的行。当那里没有行时,它会很好地添加到表中。但是,当我尝试更新行时,我的应用程序中出现错误,告诉我具有该 ID 的项目已经存在。 下面是我用于脚本的代码。任何提示将不胜感激。

function insert(item, user, request) {
var table = tables.getTable('Reviews');
table.where({ 
   text: item.id
}).read({
   success: upsertItem
});

function upsertItem(existingItems) {
    if (existingItems.length == 0) {
        item.numReviews = 1;
        item.rating = item.reviews;
        request.execute();
    } else {
        item.id = existingItems[0].id;
    item.numReviews = existingItems[0].numReviews + 1;
    var average = existingItems[0].reviews / item.numReviews;
    item.reviews = existingItems[0].reviews + item.reviews;
    item.rating = average;
      table.update(item, {
        success: function(updatedItem) {
            request.respond(200, updatedItem)
        }
      });
    }
 }

}

【问题讨论】:

    标签: javascript android azure azure-mobile-services serverside-javascript


    【解决方案1】:

    对于您的初始查询,您希望通过 id 字段进行查询:

    table.where({
        id: item.id
    }).read({
        success: upsertItem
    });
    

    编辑:进一步说明 您的查询对象 {text: item.id} 被有效地转换为 SQL 查询 select * from Reviews where text = item.id 其中 item 是 POST 正文。因此,您的代码示例正在搜索文本列中包含 id 值的评论。它没有找到任何内容,因此 upsert() 回调函数 if 语句评估为 true,因为 existingItems 为空,并尝试通过调用 request.execute() 来插入该项目。

    根据我建议的更改,使用{id: item.id},变成类似的查询 select * from Reviews where id = item.id 因此它将在 id 列中搜索具有匹配 id 值的评论。

    【讨论】:

    • 感谢 Eric 的回复。不幸的是,它没有成功。由于某种原因,它没有执行更新。它尝试插入已经存在的项目而不是更新它。关于它为什么会这样做的任何想法?
    • 我用更多的解释更新了我的答案。这更有意义吗?
    • 感谢@Eric,我终于明白了:)
    猜你喜欢
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2016-08-02
    • 1970-01-01
    • 2014-07-04
    • 2012-11-01
    相关资源
    最近更新 更多