Contentop
Contentop

Reputation: 1241

Put in table if item does not exist in DynamoDB

I want to add an item only if it does not exist. I am not sure how to do it. Currently I am adding successfully without checking the condition (it adds regardless if the item exists). The code is:

const params = {
    TableName: MY_TABLE,
    Item: myItem
};


documentClient.put(params).promise()
    .catch(err => { Logger.error(`DB Error: put in table failed: ${err}`) });

}

What do I need to add in order to make the code check if the item exists and if it does, just return?

Note: I do not want to use the database mapper. I want the code to the be written using the AWS.DynamoDB class

Upvotes: 0

Views: 2496

Answers (2)

Iris Hunkeler
Iris Hunkeler

Reputation: 208

DynamoDB supports Conditional Writes, allowing you to define a check which needs to be successfull, for the item to be inserted/updated.

Upvotes: 1

Philip Kendall
Philip Kendall

Reputation: 4314

DynamoDB is not an SQL database (hopefully you know this...) and does not offer the full set of ACID guarantees. One of the things you can't do with it is an atomic "check and write" - all you can do is fetch the item, see if it exists and then put the item. However, if done other process wires the item to the table between your "get" and your "write", you won't know anything about it.

If you absolutely need this kind of behaviour, DynamoDB is not the right solution.

Upvotes: 0

Related Questions