[Fixed] Update part of attributes in DynamoDB

Use below codes, I successfully update an item

Then I add more attributes:

  const params = {
    TableName: process.env.DYNAMODB_TABLE,
    Key: {
      id: event.pathParameters.id,
    },
    ExpressionAttributeNames: {
      '#user_name': 'name',
    },
    ExpressionAttributeValues: {
      ':name': data.name,
      ':email': data.email,
      ':username': data.username,
      ':password': data.password,
      ':checked': data.checked,
      ':updatedAt': timestamp,
    },
    UpdateExpression: 'SET #user_name = :name, email = :email, username = :username, password = :password, checked = :checked, updatedAt = :updatedAt',
    ReturnValues: 'ALL_NEW',
  };

Above codes work fine if I feed all attributes.

$ cat test/user-1.json
{
  "name": "Bob",
  "email": "bob@example.com",
  "username": "bob",
  "password": "adfdsfdsf",
  "checked": false
}

But if I only want to update part of them, since I needn’t update email and password every time, I got error Couldn't fetch the user item.

$ cat test/user-1.json
{
  "name": "Bob",
  "username": "bob-1",
  "checked": false
}

$ curl -X PUT ${url}/${id} --data '@test/user-1.json'
Couldn't fetch the user item.

So how to change the code that I don’t have to update all attributes.

You need to look at data.email and data.password to see if they’re defined then dynamically generate the UpdateExpression and ExpressionAttributeValues so they only contain the values being updated.

1 Like

Thanks, @buggy. Looks this is the only solution.

I plan to get() from id first and compare with event.body, if email is in body key list, then I use it from event.body, otherwise, replace with exist email from get()

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#get-property

Hi, I am using nodejs, is there any way to dynamically generate the ExpressionAttributeValues and the UpdateExpression for a nested json object like:
{
“id”: “12345”,
“sub”:{
“firstname”: “John”,
“lastname”: “Doe”,
“type”:{
“tyepid”: “7”,
“typename”: “ch”,
“otherole”: “other role”
},
“email”: "k.d@abc.com"
}}