Question:
I have a product table in DynamoDB which has some items. Now I need to add list of buyers to the product which can grow i.e. append to list. It works for if I have an empty list or a list with some items in the table item but for the first addition it throws an error. Is there any way to check if list exists then append else add a list. here is my code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let params = { TableName: "product", ExpressionAttributeNames: { "#Y": "buyer" }, ExpressionAttributeValues: { ":y": ["PersonXYZ"] }, Key: { id: 'Hy2H4Z-lf' }, UpdateExpression: "SET #Y = list_append(#Y,:y)" }; updateItemInDDB(params).then((data) => { res.status(200).send(data); }, err => { console.log(err); res.sendStatus(500); }); |
UpdateItemInDDB is just a function which takes a params and run dnamodb code on it. I am using javascript sdk for DynamoDB with Document Client.
Answer:
EDIT: Nest the conditional expressions
You could run SET append_list with a ConditionalExpression that the attribute does exist, then if that fails run SET with a ConditinalExpression that the attribute does not exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
let params1 = { TableName: "product", ExpressionAttributeNames: { "#Y": "buyer" }, ExpressionAttributeValues: { ":y": ["PersonXYZ"] }, Key: { id: 'Hy2H4Z-lf' }, ConditionExpression: "attribute_exists(buyer)", UpdateExpression: "SET #Y = list_append(#Y,:y)" }; updateItemInDDB(params1).then((data) => { res.status(200).send(data); }, err => { console.log(err); let params2 = { TableName: "product", ExpressionAttributeNames: { "#Y": "buyer" }, ExpressionAttributeValues: { ":y": ["PersonXYZ"] }, Key: { id: 'Hy2H4Z-lf' }, ConditionExpression: "attribute_not_exists(buyer)", UpdateExpression: "SET #Y = (#Y,:y)" }; updateItemInDDB(params2).then((data) => { res.status(200).send(data); }, err => { console.log(err); res.sendStatus(500); }); }); |