Reputation: 49
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
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:
undefined
on the ItemUpvotes: 1
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