4

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);
    });
}

1 Answer 1

1

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
};
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.