0

I'm using Azure Mobile Services with an android application which I am trying to get working with a SQL database in Azure. Im using a server-side JavaScript function within Mobile Services to handle the insertion and update of data. Insertion of new data operates correctly, however I cannot update any rows with the function.

The error I received is: 409 - error: Could not insert the item because an item with that id already exists. It seems as though it is trying to insert instead of update, but I can't figure out the solution. Help is much appreciated! Here's my server-side script from Azure:

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)
            }
        });
    }
  }
}    
Mark
  • 535
  • 4
  • 13

1 Answers1

0

For your initial query, you want to query by the id field:

table.where({
    id: item.id
}).read({
    success: upsertItem
});
Eric Hedstrom
  • 1,627
  • 10
  • 13