1
votes

I need to insert a document if the primary key doesn't exist. I have tried to solve this using conditionExpression but it seems to fail.

const primaryKey = "4234241";
const tableSpec = {
    TableName: 'tableName',
    Item: params,
    ConditionExpression: '#primaryId <> :primaryId',
    ExpressionAttributeNames: {'#primaryId': 'primaryId'},
    ExpressionAttributeValues: {
        ':primaryValue': primaryValue
    }
  };
  var docClient = new AWS.DynamoDB.DocumentClient();
  docClient.put(tableSpec, function (err, data) {
    if (err) {
      console.log(err);
    }
  });

"ConditionalCheckFailedException: The conditional request failed" is the output of the console.log statement.

2

2 Answers

2
votes

Is it throwing the exception when an object with this primary key exists? Than it's fine, just catch an exception, process it if you need to (maybe log that object exists already) and move on.

With this you will make one call it will either return success if an object was created or an exception (that you can catch and ignore) if an object already exists.

0
votes

The only solution of ConditionalCheckFailedException is getting and check before insert.