Search code examples
amazon-dynamodbaws-sdkaws-sdk-js

DynamoDb Nested Map Update


After working a bit with DynamoDb I’ve run into an issue that from what I’ve read so far is not really ideal for DynamoDb. So before I make the switch to RDS, I’d like to see if there’s anyway I can achieve what I need with DynamoDb. I’ve also thought about breaking this out into multiple tables for DynamoDb

Below of my Data schema. There is a list nested inside the item. I need to be able to append strings to the list.

{
    “server-id”: “123345678”,
    “server-name”: “my-server”
    “topics”: [
        {
            “name”: “my-topic”,
            “subscribers”: [] //This is what I need to append
        }
     ]
}

Solution

  • Yes, this is possible.

    var AWS = require('aws-sdk');
    AWS.config.update({region: 'us-east-1'});
    var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
    
    var params = {
      ExpressionAttributeNames: {
       "#T": "topics", 
       "#S": "subscribers"
      }, 
      ExpressionAttributeValues: {
        ":vals": {
          L: [
            { N: "123" },
            { N: "456" }
          ]
        }
      }, 
      Key: {
       'server-id': { S: '123345678' }
      }, 
      ReturnValues: "ALL_NEW", 
      TableName: 'dummy-table',
      UpdateExpression: "SET #T[0].#S = list_append(#T[0].#S, :vals)"
     };
    
    ddb.updateItem(params, function(err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });