I am running an AWS Lambda service written in Node.js that interacts with a DynamoDB database. One of my methods performs an update (AWS.DynamoDB.DocumentClient().update) on
You can use ConditionExpression
for this. The update will happen if the key (i.e. userId) is present and update attribute (i.e. isActive) is not equal to the new value that you are trying to update.
ConditionExpression: "userId = :userIdVal and isActive <> :isActiveVal",
ExpressionAttributeValues: {
':isActive': 'false',
':userIdVal': '123'
},
EDIT:-
This should work. It should be ConditionExpression
(not ConditionalExpression).
var params = {
TableName: 'users',
Key: {
'userId': '123'
},
UpdateExpression: 'SET isActive = :isActiveVal',
ConditionExpression: 'userId = :userIdVal and isActive <> :isActiveVal',
ExpressionAttributeValues: {
':userIdVal': '123',
':isActiveVal': 'false'
},
ReturnValues: "ALL_NEW"
};
Update, 2020:
You can use attribute_exists
in ConditionExpression
to check if the item exists or not. (Sources: 1, 2)
const params = {
TableName: 'users',
Key: {
'userId': '123'
},
UpdateExpression: 'SET isActive = :isActiveVal',
ConditionExpression: 'attribute_exists(userId)',
ExpressionAttributeValues: {
':isActiveVal': 'false'
},
ReturnValues: "ALL_NEW"
};