FlightHoldings
FlightHoldings

Reputation: 49

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");
                    }

}

Upvotes: 1

Views: 8592

Answers (2)

inmyth
inmyth

Reputation: 9050

Two things to add:

Item is for GetItem, Items is for Query.

Also AWS documentation mentions ResourceNotFoundException "for the operation that tried to access a nonexistent table or index". To avoid the confusion:

  • Getting a non-existing item will return undefined on the Item
  • Trying to get something from non-existing table or non-existing index will cause that error. For example you mistype the table name or the primary index.

Upvotes: 1

jarmod
jarmod

Reputation: 78573

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.

Upvotes: 2

Related Questions