Search code examples
aws-lambdaamazon-dynamodbaws-serverlessaws-sdk-jsaws-sdk-nodejs

DynamoDB: Using SET on an UpdateExpression to increment a field is not working


I'm following the AWS docs in order to implement a lambda to increase the value of a field with an scalar value in DynamoDB. In my case I'm using NodeJS SDK v3, but the docs redirect you to this page at some point.

My problem is that the SET command in UpdateExpression is not working when I use to increase the value of some fields.

This is an example of how I initialize the command and execute it:

const params = {
  TableName: 'MyTable',
  Key: { id: 'my-id' },
  ExpressionAttributeNames: {
    '#credit': 'user.credit',
  },
  ExpressionAttributeValues: {
    ':creditToAdd': 100,
  },
  UpdateExpression: 'SET #credit = #credit + :creditToAdd',
  ReturnValues: 'ALL_NEW'
};

const client = new DynamoDBClient(options);
const docClient = new DynamoDBDocumentClient(client);
const command = new UpdateCommand(params);
const updateUserResponse = await docClient.send(command);

And this is the error I get:

ValidationException: The provided expression refers to an attribute that does not exist in the item

When I use UpdateExpressions like this:

UpdateExpression: 'SET #credit = :creditToAdd',

I have no problems, only fails when I put some operands on it.

On my tests, I tried to use ADD instead of SET, and it works:

UpdateExpression: 'ADD #credit :creditToAdd',

but as you can see in the docs:

In general, we recommend using SET rather than ADD.

and the true is that I prefer to use it with SET to combine it with the update of other fields, like the timestamp of the date of the last credit addition.

What am I doing wrong?


Solution

  • The SET requires that the attribute user.credit exists BEFORE the update. In comparison ADD will work on an item that doesn't have the field defined.

    Most likely the issue in your test is that field doesn't have an initial value.