How to prevent creating a new item in UpdateItem if the item does not exist

前端 未结 3 1607
鱼传尺愫
鱼传尺愫 2020-12-29 17:53

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

3条回答
  •  感情败类
    2020-12-29 18:37

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

提交回复
热议问题