Search code examples
arraysamazon-web-servicesamazon-dynamodbis-empty

Check if a table item doesn't exist. How to check returned 'Items' array if empty? Javascript/DynamoDB


I am trying to see if an item exists in the DynamoDB database. However I can't find a straight forward answer. So I am using the getItem() operation.

This returns a JSON. In the documentation it says that the Item returned should be empty if no item was found in the database. However, I can't seem to figure out how to check if this returned value is empty. I have tried variations of if(data == "undefined"){

//PutItem - DynamoDB table: check if group exists
                var dynamodb5 = new AWS.DynamoDB({ region: AWS.config.region });
                var identityId = AWS.config.credentials.identityId;
                var params = {
                      Key: {
                       "groupName": {
                         S: groupname
                        }
                      }, 
                      TableName: "group"
                     };
                dynamodb5.getItem(params, function(err, data) {
                if (err){
                    console.log(err, err.stack); // an error occurred
                     alert("This group doesnt exist.")
                }else{
                   // successful response console.log(data); 


                    if(data.Items[0] == "undefined"){
                        console.log("ITS WORKING");
                    }

}


Solution

  • The getItem response doesn't include Items, it includes Item (see the documentation). It will return one item, if there is an item with the given key, or no item.

    You can detect this as follows:

    const AWS = require('aws-sdk');
    
    const ddb = new AWS.DynamoDB({ region: 'us-east-1' });
    
    const params = {
      Key: {
        'groupName': {
          S: groupname,
        },
      },
      TableName: 'group',
    };
    
    ddb.getItem(params, (err, data) => {
      if (err) {
        console.log(err, err.stack);
      } else if (data.Item) {
        console.log(JSON.stringify(data));
      } else {
        console.log('Success, but no item');
      }
    });
    

    Minor note: there's little reason to use var now that we have let and const.