Search code examples
amazon-dynamodb

How to do a DynamoDB put only when PK and SK don't already exist?


I have code that checks if a given item exists at a given primary key on a table that just uses a PK and puts the item in the DB if it wouldn't be overwriting:

    let params = {
        TableName: process.env.NIMS_TABLE_NAME,
        Item: { ...userObj, PK: userObj.sid },
        ConditionExpression: "attribute_not_exists(PK)", 
    };

    try {
        await docClient.put(params).promise();
        return { success: true, sid: userObj.sid };
    } catch (err) {
        if (err.message === "The conditional request failed") {
            err.message += ` (Item at sid (${userObj.sid}) already exists)`;
        }
        callback(new Error(`[422] ${err.message}`));
    }

Now, I'm moving to a table with a PK and an Sort Key and I'm not sure how to avoid overwriting a given PK/SK combo? How do I say, effectively, ConditionExpression: "attribute_not_exists(PK,SK)" or similar?


Solution

  • You don't need to change anything. Your condition will always evaluate the one item your writing, before just PK, now PK/SK combo. A condition on either the PK, the SK or both will work. So in your case there's nothing to change.