Search code examples
aws-lambdaamazon-dynamodbaws-sdkaws-sdk-nodejs

How to call single item with DynamoDB?


I'm trying to call getItem to DynamoDB. I'm using code samples from the documentation, however, all that I'm getting is null.

  • I have a table called table.
  • I have table row with Primary partition key called id (number).
  • I don't have Primary sort key.
  • Lambda function has the permission of Allow: dynamodb:GetItem

My item with id of 123 has few more rows attached to it, and I'd like to retrieve them all in the console log.

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({ region: 'eu-central-1' });

exports.handler = async (event) => {

  // Create the DynamoDB service object
  ddb = new AWS.DynamoDB({ apiVersion: '2012-10-08' });

  var params = {
    TableName: 'table',
    Key: {
      'id': { N: '123' },
    }
  };

  // Call DynamoDB to read the item from the table
  ddb.getItem(params, function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data.Item);
    }
  });

};

Solution

  • var AWS = require('aws-sdk');
    // Set the region 
    AWS.config.update({region: 'REGION'});
    exports.handler = (event, context, callback) => { 
    // Create the DynamoDB service object
    ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'});
    
    var params = {
      TableName: 'TABLE',
      Key: {
        'KEY_NAME' : {N: '123'},
      },
      ProjectionExpression: 'ATTRIBUTE_NAME'
    };
    
    // Call DynamoDB to read the item from the table
    
    ddb.getItem(params, function(err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data.Item);
      }
    });
    }
    

    This is my lambda example you can try it.