Reputation: 41
how do i conditional update item in dynamoDB using nodejs? If exists, just do an increment alone - it is working as expected. But I am struggling in, when the item is not exists, need to add it and next iteration onwards do increment. got this error "The provided expression refers to an attribute that does not exist in the item".
function increment(data, cb) {
const opt = {
Key: {
id: {S: id},
dateKey: {S: data.dateVal}
},
ExpressionAttributeValues: {
':counter': {N: '' + 1},
':val1': {S: data.val1},
':val2': {S: data.val2}
},
UpdateExpression: 'SET counter=counter+:counter, val1=:val1, val2=:val2',ReturnValues: 'UPDATED_NEW',
TableName:tableName
};
db.updateItem(opt, (err, data) => {
if (err)
return cb(err);
const counter = getCounter(data.Attributes); //private method
return cb(null, counter);
});
}
Upvotes: 4
Views: 2369
Reputation: 11215
If the item you are incrementing does not exist, you can assume the initial value to be 'zero' as shown bellow:
const opt = {
Key: {
id: {S: id},
dateKey: {S: data.dateVal}
},
ExpressionAttributeValues: {
':counter': {N: '' + 1},
':val1': {S: data.val1},
':val2': {S: data.val2},
':zero': {N: 0}
},
UpdateExpression: 'SET counter=if_not_exists(counter, :zero)+:counter, val1=:val1, val2=:val2',ReturnValues: 'UPDATED_NEW',
TableName:tableName
};
Upvotes: 1