5

I have a dynamoDB table that has an Item that includes a UserId and a List of lists. It looks like this:

Item: 
{
    UserId: 'abc123',
    Lists: [
        {
            id: 1,
            title: 'My favorite movies',
            topMovies: [
                {
                    id: 1,
                    title: 'Caddyshack'
                },
                {
                    id: 2,
                    title: 'Star Wars'
                }
            ]

        }
    ]
}

Now, lets the user has created a new list titled, "My favorite TV Shows", and wants to insert it into the Lists array with id: 2.

How would I update this object using document client. I've looked through several examples and I've found nothing that explains what I'm trying to do. It's making me think that perhaps I'm not using DynamoDB correctly and I should have a different object schema.

I've attempted using this, but it is overwriting my previous object.

exports.handler = (event, context, callback) => {
console.log(event);
const params = {
    TableName: "top-ten",
    Key: {
        "UserId": 'abc123',
    },
   UpdateExpression: "set Lists =:newItem",
   ExpressionAttributeValues: {
        ":newItem": {
            "id": 2,
            "title": "Favorite TV Shows",
            "topMovies": [{"id": 1, "title" : "The Simpsons"}]

        },
    },
    ReturnValues: "UPDATED_NEW"
};
dynamodb.update(params, function(err, data) {
    if (err) {
        console.log(err);
        callback(err);
    } else {
        console.log(data);
        callback(null, data);
    }
});

};

EDIT: Ok, I've figured out that if I put

 UpdateExpression: "set Lists[1] =:newItem" 

it updates the item correctly. But now, how do I know how many items I have in my list array?

1 Answer 1

8

You should use list_append. The function adds two lists together, so you need to make your item to add a list.

exports.handler = (event, context, callback) => {
console.log(event);
const params = {
    TableName: "top-ten",
    Key: {
        "UserId": 'abc123',
    },
UpdateExpression : "SET #attrName = list_append(#attrName, :attrValue)",
ExpressionAttributeNames : {
  "#attrName" : "Lists"
},
ExpressionAttributeValues : {
  ":attrValue" : [{
            "id": 2,
            "title": "Favorite TV Shows",
            "topMovies": [{"id": 1, "title" : "The Simpsons"}]

        }]
},
ReturnValues: "UPDATED_NEW"
};
dynamodb.update(params, function(err, data) {
    if (err) {
        console.log(err);
        callback(err);
    } else {
        console.log(data);
        callback(null, data);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.