0

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

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

}

回答

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值搜索Review。

+0

感谢您的回复埃里克。不幸的是,没有做到这一点。由于某种原因,它不执行更新。它试图插入已有的项目,而不是更新它。任何想法为什么它可能会这样做? – 2015-03-26 10:25:37

+0

我更新了我的答案,更多的解释发生了什么事。这是否更有意义? – 2015-03-27 15:24:24

+0

谢谢你@Eric我最终得到了它:) – 2015-03-27 19:26:01

相关问题