1

Structure of an item in database is as shown below:

{
    "cars": {
        "x": [
            {
                "time": 1485700907669,
                "value": 23
            }
        ]
    },
    "date": 1483214400000,
    "id":"1"
}

I have to add a new item "z" of type list to cars like

{
    "cars": {
        "x": [
            {
                "time": 1485700907669,
                "value": 23
            }
        ],
        "z": [
            {
                "time": 1485700907669,
                "value": 23
            }
        ]
    },
    "date": 1483214400000,
    "id": "1"
}

What would the update expression in Node.js look like if I want to achieve somethings like this? So far this is what I came up with: set #car.#model= list_append(if_not_exists(#car.#model, :empty_list), :value)

However, if the item does not exist at the time of creation it throws error. Any idea how to do this?

This is the updated parameter I am using, still doesn't work

  var params = {
  TableName:table,
  Key:{
      "id": id,
      "date": time.getTime()
  },
  ReturnValues: 'ALL_NEW',
  UpdateExpression: 'SET #car.#model = if_not_exists(#car.#model,     
  :empty_list)',
  ExpressionAttributeNames: {
    '#car': 'cars',
    '#model':"z"
  },
  ExpressionAttributeValues: {
    ':empty_list': [],
  }
 };

2 Answers 2

1

The solution is to update operation in two steps, first create a empty map for the parent since it does not exist in the first place. So, in my case

SET #car= :empty_map

where :empty_map = {}

after doing this run the other update expression

SET #car.#model = list_append(if_not_exists(#car.#model, :empty_list), :value)

where :empty_list=[] and :value= { "time": 1485700907669, "value": 23 }

Sign up to request clarification or add additional context in comments.

1 Comment

Glad you worked it out :) What I understood from your original question was that you always had a parent #car and you were just trying to add an element to the #model list, which might not exist.
0

Break your update expression apart into two separate expressions:

SET #car.#model = if_not_exists(#car.#model, :empty_list) SET #car.#model = list_append(#car.#model, :value)

4 Comments

Is there no way to do it in a single statement?
Not to my knowledge, no.
I tried this part alone SET #car.#model = if_not_exists(#car.#model, :empty_list) . It doesnt work. Gives error : "The document path provided in the update expression is invalid for update",
Can you please provide the complete working code (including the values for :empty_list and :value) in order to re-produce the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.