user6680
user6680

Reputation: 139

DynamoDB remove Map from List where property equals value

How can I remove a map inside of a list in dynamo using a property value?

This is the dynamo record structure

{
  "authorizedUsers": [
    {
      "name": "Bob",
      "phoneNumber": "822-222-2221"
    },
    {
      "name": "Joe",
      "phoneNumber": "111-111-2221"
    }
  ],
  "PK": "users"
}

currently I have


    var params = {
        TableName: 'userTable',
        Key: {
            PK: 'users'
        },
        UpdateExpression: 'REMOVE authorizedUsers[0]',
        ReturnValues: 'UPDATED_NEW'
    };

    try {
        await docClient.update(params).promise();
    } catch (e) {
        throw new Error(e.message);
    }

and this removes the first record no problem, but I need the expression to be more dynamic and be able to remove the row by phoneNumber (unique identifier) How can I modify this to use the phoneNumber to identify the correct Map inside List to remove?

Upvotes: 1

Views: 300

Answers (1)

Ross Williams
Ross Williams

Reputation: 630

You cannot use the phoneNumber to identify a map item inside the list.

You state that phoneNumber is a unique identifier. I suggest to change the model of your item to not use arrays, and instead use a map with the phoneNumber as the key.

{
  "authorizedUsers": {
    "822-222-2221": {
      "name": "Bob",
      "phoneNumber": "822-222-2221"
    },
    "111-111-2221": {
      "name": "Joe",
      "phoneNumber": "111-111-2221"
    }
  ,
  "PK": "users"
}

If you cannot change the structure of the item, consider versioning the item and over-writing the whole authorizedUsers array attribute. You will want to create a Version_ID on all items as a one off operation (or don't and assume an implicit version of 0 for all items without a version number).

When you want to update an authorizedUsers attribute on an item, first read the item. Then create an Update operation with the new array, and also increment the Version_ID attribute. Finally, add a ConditionExpression to check the Version_ID attribute value is still the value when you first read the item, to make sure another process hasn't updated the item in the meantime.

Upvotes: 3

Related Questions