Pljeskavica
Pljeskavica

Reputation: 114

Add a string to a list in a dynamodb table

So I have been working with dynamodb in a nodejs express app and I have a specific table that has a field which is just empty lists and I want to append a string to the list.

The table name is "dev_entrants" and here is an example of the table:

----------------------------------------
primary Key           Sort Key    
eventID            | eventType  | entrants
----------------------------------------
Qual-919-w5wm1xhnw | Qual       | []

----------------------------------------

So I receive a post request and then route it through express and it comes to a function where after doing type checks and all that I try to add stuff to my table with:

import AWS from 'aws-sdk';

const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-west-1'});

const db = {
  docClient
};

...

const entrantsParams = {
    'TableName' : 'dev_entrants',
    'Key': {
      'eventID' : 'Qual-919-w5wm1xhnw',
    },
    'UpdateExpression' : "SET #attrName = list_append(#attrName, :attrValue)",
    'ExpressionAttributeNames' : {
      '#attrName' : 'entrants'
    },
    'ExpressionAttributeValues' : {
      ':attrValue' : ['joe'],
    }
  };

  const updateEntrantsPromise = db.docClient.update(entrantsParams).promise();

(For the purpose of this example I have replaced variables with the strings they represent)

I have spent 6 hours or so reading through different documentation, as well as on stack overflow trying to find the answer.

The current error i get is the provided key element does not match the schema. If I remove the brackets around the attrValue then I get wrong operand type. I know the key exists in the table as i copied and pasted it from there. Also I am succesfully adding things to the table from another function so my connection is working fine. Can anyone please help me out?

Upvotes: 3

Views: 2714

Answers (1)

idbehold
idbehold

Reputation: 17168

You need to include the eventType in the Key object because your table schema has a sort key. If your table has a sort/partition key then you need to include it along with the primary key. Try it with the following:

const entrantsParams = {
  'TableName' : 'dev_entrants',
  'Key': {
    'eventID' : 'Qual-919-w5wm1xhnw',
    'eventType' : 'Qual'
  },
  'UpdateExpression' : "SET #attrName = list_append(if_not_exists(#attrName, :empty_list), :attrValue)",
  'ExpressionAttributeNames' : {
    '#attrName' : 'entrants'
  },
  'ExpressionAttributeValues' : {
    ':attrValue' : ['joe'],
    ':empty_list': []
  }
};

Upvotes: 8

Related Questions