1

I am new to DynamoDB and want only to create a new object if the Primary sort key(name) does not exist twice. I tried it like this:

params.id = randomId();

        var item = {
            TableName: tableName,
            Item: params,
            ConditionExpression: "#na <> :n",
            ExpressionAttributeNames:{"#na":"name"},
            ExpressionAttributeValues:{
                ":n":params.name
            }
        };

        docClient.put(item, function(err, data) {
            console.log("Data:", data);
            console.log("Err:", err);
        });

But the item is still created :/ Is ist even possible to create a condition expression on the primary sort key ?

jjuser19jj
  • 1,637
  • 3
  • 20
  • 38

2 Answers2

0

Actually just ran into this issue myself, as explained here it looks like you can't, you'll have to use a Global Secondary Index for the 'sort' key.

You will have to do a seperate get request on the GSI first to see if "name" exists for eg.

function checkNameDoesNotExist(name, fn){

    query.IndexName = 'nameInUsers';
    query.KeyConditionExpression = 'name = :n';
    query.ExpressionAttributeValues = {
        ':n': name
    };

    dynamodb.query(query, function(err, data){
        if (err) {
            return fn(err);
        } else {
            fn(null, data);
        }
    });
}

Disclaimer: wrote the code off the top of my head, don't know if it works but should give you a good starting point

csilk
  • 2,732
  • 3
  • 23
  • 40
0

You can use the exist condition. It will return an error saying that the object already exists

var item = {
    TableName: tableName,
    Item: params,
    Expected: {
    name: {
      Exists: false
    }
};

docClient.put(item, function(err, data) {
    console.log("Data:", data);
    console.log("Err:", err);
});
Leonardo Alves
  • 1,876
  • 1
  • 16
  • 19