title: Expected constraint in dynamodb to prevent duplicates
body: <p>I am new to DynamoDB and I am having trouble getting the following scenario to work in node.js and DynamoDB:</p>
  
  <p>I want to insert a user in a user table but I don't want this to succeed if the user's email address already exists.</p>
  
  <p>The following code is able to successfully insert a new user:</p>
  
  <pre><code>var item = {
      id: { S: uuid.v4()},
      email: { S: 'my@email.com' }
  };
  
  dynamodb.putItem({
      TableName: 'user',
      Item: item,
      Expected: {
          email: { Exists: false }
      }
  }, function (err, data) {
      if (err) {
          return callback(err);
      }
      callback();
  });
  </code></pre>
  
  <p>I assumed the Expected value would prevent duplicate email addresses in the user's table by raising an ConditionalCheckFailedException error. This is not the case; the code above will insert duplicate emails consistently. I tried adding the 'id' as an additional Expected field but this didn't change the behavior.</p>
  
  <p>I do get a ConditionalCheckFailedException when I modify the code so the ID is fixed rather than a generated UUID;</p>
  
  <pre><code>var item = {
      id: { S: 'Test' },
      email: { S: 'my@email.com' }
  };
  </code></pre>
  
  <p>I should explain, the 'id' is the hash key and 'email' is the range key.</p>
  
  <p>This behavior led me to believe the constraints only work on the record specified with the hash key. If that were the case the AWS documentation would be very confusing indeed (I highlighted in bold what confuses me):</p>
  
  <blockquote>
    <p>If Exists is false, Amazon DynamoDB assumes that the attribute value <strong>does not exist in the table</strong>. If in fact the value does not exist, then the assumption is valid and the operation succeeds. If the value is found, despite the assumption that it does not exist, the operation fails with a ConditionalCheckFailedException.</p>
  </blockquote>
  
  <p>Assuming the documentation is correct I must be doing something wrong? Any help would be much appreciated!</p>
  
  <p><strong>EDIT 2013-11-09</strong></p>
  
  <p>Based on the comment below I decided to change tactics. I'm a bit reluctant to use a value that I need to reference in most other domain objects that isn't immutable. I now have an email address table that acts as a lookup / index table for user ID's. This allows me to have the user change his or her email address quite easily (I could even support multiple email addresses). </p>
  
  <p>Thanks for the help!</p>