0

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

Contentop
  • 1,163
  • 3
  • 20
  • 43

2 Answers2

1

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

Iris Hunkeler
  • 208
  • 1
  • 10
0

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.

Philip Kendall
  • 4,304
  • 1
  • 23
  • 42
  • What you are saying is good enough for me. I saw a simmilar thread about this: https://stackoverflow.com/questions/46531331/how-to-prevent-a-dynamodb-item-being-overwritten-if-an-entry-already-exists But the problem is that I dont want it to throw if the item exists, just disregard – Contentop Aug 04 '19 at 07:19