DynamoDB update fails when nested path not exists

Viewed 288

My table structure is below where time is the unique key and that "01" was the id of the count, the item of a month will create right after any id get the count result of that month.

{
  "details": {
    "01": {
      "a": {
        "count": [10, 5]
      },
      "b": {
        "count": [10, 5]
      }
    }
  },
  "time": "2020_06"
}

And I use update function to save the count result:

var params = {
  TableName: tableName,
  Key: { time },
  UpdateExpression: `ADD details.#id.#type.count[0] :count0, details.#id.#type.count[1] :count1`,
  ExpressionAttributeNames: {
    '#id': id,
    '#type': type
  },
  ExpressionAttributeValues: {
    ':count0': count[0],
    ':count1': count[1]
  },
  ReturnValues: 'ALL_NEW'
}

If the result of the id already exists then that's fine. But if it doesn't, I'll get an error says that

ValidationException: The document path provided in the update expression is invalid for update

How to let the map be constructed before updating data? I had tried to use SET if_not_exists() but it'll overlap the path what I really want to update (the count array)

0 Answers
Related