0
votes

I want to update an existing item within a AWS DynamoDB via node.js. I only have a secondary index value of the item I want to update. I cannot access the primary index...

Id: primary index
CallId: global secondary index
CallStatus: normal field

I want to update the CallStatus just by using the CallId (without using the key).

I tried different approaches like:

  • Scan for item and then update with fetched primary key
  • Query by GSI and then update
  • Conditional update

But none of this methods worked for me. I assume, because I`m not using them correctly. Any help appreciated :-).

Code example for the "scan and update" method:

  var docClient = new aws.DynamoDB.DocumentClient();
  var params = {
    TableName: 'myTable',
    FilterExpression: 'CallId = :c',
    ExpressionAttributeValues: {
      ':c': callSid
    }
  };

  docClient.scan(params, function (err, result) {
    if (err) {
      console.error("Unable to query item. Error JSON:", JSON.stringify(err));
    } else {
      console.log(result);

      // Update call status
      var params = {
        TableName: "myTable",
        Key: {
          "Id": result.Items[0].Id
        },
        UpdateExpression: "set CallStatus = :s",
        ExpressionAttributeValues: {
          ":s": callStatus
        },
        ReturnValues: "UPDATED_NEW"
      };

      docClient.update(params, function (err, data) {
        if (err) {
          console.error("Unable to update item. Error JSON:", JSON.stringify(err));
        } else {
          console.log("Update item succeeded:", JSON.stringify(data));
        }
      });
    }
  });
1
Are you getting any error? what do you mean by "Key: primary index"? Partition key attribute name is "Key" or "Id"? - notionquest
@notionquest Sadly no error message, the primary key is named Id, I changed that in my question above, - Tobias

1 Answers

3
votes

Okay, I´ve found my error. The call after the update above should happen closed the AWS Lambda session, thus the async update of the DynamoDB never happend...

The now working code reads as follows:

  var params = {
    TableName: 'table',
    IndexName: 'CallId-index',
    KeyConditionExpression: 'CallId = :id',
    ExpressionAttributeValues: {
      ':id': callSid
    }
  };

  docClient.query(params, function (err, result) {
    if (err) {
      console.log("Unable to query item. Error JSON:", JSON.stringify(err));
    } else {
      var params = {
        TableName: "table",
        Key: {
          "Id": result.Items[0].Id
        },
        UpdateExpression: "set CallStatus = :s",
        ExpressionAttributeValues: {
          ":s": callStatus
        },
        ReturnValues: "UPDATED_NEW"
      };
      docClient.update(params, function (err, data) {
        if (err) {
          console.log("Unable to update item. Error JSON:", JSON.stringify(err));
        } else {
          // do sth. else
        }
      });
    }
  });