Add non existing element to array in DynamoDB
You can use the "not contains" and "list_append" for your requirement.
The below code inserts the new friend to list if the friend is NOT already present in the list.
If the friend is already present in the list, it would throw "conditional request failed".
Error message if condition fails:-
Unable to update item. Error JSON: {
"message": "The conditional request failed",
"code": "ConditionalCheckFailedException",
"time": "2016-06-22T08:18:36.483Z",
"requestId": "86805965-240b-43e0-8fdc-77fb9ae1b15c",
"statusCode": 400,
"retryable": false,
"retryDelay": 0
}
The below code works fine. It has been tested successfully.
Code Sample:
var AWS = require("aws-sdk");
AWS.config.update({
region : "us-west-2",
endpoint : "http://localhost:8000"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "users";
var userid = 1;
var friendId = ["f4"];
var friendIdStr = "f4";
//Add the new DOCUMENT TYPE attribute to the table
var params = {
TableName : table,
Key: {
"id" : userid
},
"UpdateExpression": "set friends = list_append (friends, :friendId)",
"ConditionExpression": "not contains (friends, :friendIdStr)",
"ExpressionAttributeValues": {
":friendId": friendId,
":friendIdStr" : friendIdStr
},
"ReturnValues" : "UPDATED_NEW"
};
console.log("Updated an item...");
docClient.update(params, function(err, data) {
if (err) {
console.error("Unable to update item. Error JSON:", JSON.stringify(err,
null, 2));
} else {
console.log("Updated item:", JSON.stringify(data, null, 2));
}
});
I found this answer as I was trying to add a string to a list only if it did NOT exist.
After some research I realized I should be using a String Set instead of a list.
Here is the params I used to add an item to a string set. (It automatically handles dupe prevention)
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
const item = 'unique string to add to set';
const params = {
TableName: 'myTable',
Key: {
myId,
},
UpdateExpression:
'ADD myList :myItem',
ExpressionAttributeValues: {
':myItem': docClient.createSet([item]),
},
ReturnValues: 'UPDATED_NEW',
};
docClient.update(params);
Note: createSet will create the set if it does not exist, and add items if it already exists.