title: AWS Lambda Node Js - Increment value if exist else add element
body: <p>I want increment value if exist else add element.</p>
  <pre><code>+-----------------------+
  | id | iteration | data |
  +-----------------------+
  | 10 |         1 | foo1 |
  | 11 |         1 | foo2 |
  | 12 |         2 | foo3 |
  +-----------------------+
  </code></pre>
  <p>my code:</p>
  <pre><code>var AWS = require('aws-sdk');
  var documentClient = new AWS.DynamoDB.DocumentClient({'region': 'eu-west-1'}); 
  exports.handler = function(event, context, callback) {
  
  var params = {
    Item: {
      id: uuid,
      iteration: 1,
      data: body.data
    },
    TableName: &quot;my-table&quot;
  };
  
  documentClient.put(params, function(err, data) {
      if (err) {
        console.log(&quot;Error&quot;, err);
        const errResponse = {
          statusCode: 500,
          headers: {
            &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;
          },
          body: JSON.stringify({ Error: 500, device : &quot;DynamoDB&quot;, detail : err })
        };
        callback(null, errResponse);
      } else {
        console.log(&quot;Success&quot;, params.Items);
        const response = {
          statusCode: 200,
          headers: {
            &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;
          },
          body: JSON.stringify(&quot;thanks&quot;)
        };
        callback(null, response);
      }
    });
  
  }
  </code></pre>
  <p>My insert is OK.</p>
  <p>I try with:</p>
  <pre><code>var params = {
      TableName: &quot;my-table&quot;,
      Key:{
          &quot;id&quot;: uuid
      },
      UpdateExpression: &quot;set iteration = iteration + :val&quot;,
      ExpressionAttributeValues:{
          &quot;:val&quot;: 1
      },
      ReturnValues:&quot;UPDATED_NEW&quot;
    };
    documentClient.update(params, function(err, data) {
      if (err) {
          console.error(&quot;Unable to update item. Error JSON:&quot;, JSON.stringify(err, null, 2));
          const errResponse = {
            statusCode: 500,
            headers: {
              &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;
            },
            body: JSON.stringify({ Error: 500, device : &quot;DynamoDB&quot;, detail : err })
          };
          callback(null, errResponse);
      } else {
          console.log(&quot;UpdateItem succeeded:&quot;, JSON.stringify(data, null, 2));
          const response = {
            statusCode: 200,
            headers: {
              &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;
            },
            body: JSON.stringify(&quot;thanks&quot;)
          };
          callback(null, response);
      }
    });
  </code></pre>
  <p>Update is OK (increment -&gt; 2)</p>
  <p>But I want increment value <strong>ONLY</strong> if exist else <strong>ONLY</strong> add element. Both methods are asynchronous, how should I do?</p>