Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to or create StringSet if it doesn't exist

So this should be simple...

I want to append a string to a StringSet in a DynamoDB if it exists, or create the StringSet property if it doesn't and set the value. If we could initialize the StringSet on creation with an empty array, it would be fine, but alas we can not.

Here's what I have so far:

const companiesTable = 'companies';

dynamodb.updateItem({
  TableName: companiesTable,
  Key: {
    id: {
      S: company.id
    }
  },
  UpdateExpression: 'ADD socialAccounts = list_append(socialAccount, :socialAccountId)',
  ExpressionAttributeValues: {
      ':socialAccountId': {
        'S': [socialAccountId]
      }
  },
  ReturnValues: "ALL_NEW"
}, function(err, companyData) {
  if (err) return cb({ error: true, message: err });

  const response = {
    error: false,
    message: 'Social account created',
    socialAccountData
  };

  cb(response);
});

I've also tried...

  UpdateExpression: 'SET socialAccounts = list_append(socialAccounts, :socialAccountId)',
  ExpressionAttributeValues: {
    ':socialAccountId': {
      S: socialAccountId
    }
  },

and...

  UpdateExpression: 'ADD socialAccounts = :socialAccountId',
  ExpressionAttributeValues: {
    ':socialAccountId': {
      S: socialAccountId
    }
  },

and...

  UpdateExpression: 'SET socialAccounts = [:socialAccountId]',
  ExpressionAttributeValues: {
    ':socialAccountId': socialAccountId
  },

and...

  UpdateExpression: 'ADD socialAccounts = :socialAccountId',
  ExpressionAttributeValues: {
    ':socialAccountId': socialAccountId
  },

Among about every other variation of the above. Am I dumb? Is DynamoDB not capable of simple write/updates to an array type field? Do I REALLY have to lookup the item first to see if it has that field before I try to either add or set that field, because I can't instantiate that field with an empty array?

like image 261
Steven Bennett Avatar asked Aug 18 '16 03:08

Steven Bennett


Video Answer


1 Answers

The ADD action handles the create/update logic, but only supports numbers and sets. You are trying to add a string type 'S'. You need to wrap this string in an array and pass it as a string set 'SS'. You also don't need the equals sign.
Your UpdateExpression and ExpressionAttributeValues should look like this:

 UpdateExpression: 'ADD socialAccounts :socialAccountId',
 ExpressionAttributeValues: {
   ':socialAccountId': {
      'SS': [socialAccountId]
    }
 },

More information about updating items can be found here

like image 188
Jonathan Seed Avatar answered Sep 28 '22 07:09

Jonathan Seed