DynamoDB Scan with Lambda not returning elements

Viewed 194

I have a Lambda with the following code:

// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk");
// Set the AWS Region.
AWS.config.update({ region: "us-east-2" });

 
exports.handler =  function(event, context, callback) {
    // Create DynamoDB service object.
    var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });
    
    var params = {
       TableName: "Ranking",
       ProjectionExpression: "#username, Score, Duration",
       FilterExpression: "#username = :username",
       ExpressionAttributeNames: {
          "#username": "Username",
       },
       ExpressionAttributeValues: {
            ":username": {
               S: 'Alberto'
            },
       }
    };
    
    
    
    let toReturn = [];
    ddb.scan(params, function (err, data) {
      if (err) {
        toReturn = err
      } else {
        toReturn = data.Items;
      }
    });
    let response = {
        statusCode: 200,
        body: JSON.stringify(toReturn)
    };
    callback(null, response)
};

However I always see [] as response...

My current DB has the following records: enter image description here

So my question is... why I don't get back that item?

1 Answers

Since you are using callbacks, your code should be as below. Also Duration is reserved keyword, so it also needs to be modified as below:

// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk");
// Set the AWS Region.
AWS.config.update({ region: "us-east-2" });
 
exports.handler =  function(event, context, callback) {
    // Create DynamoDB service object.
    var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

    var params = {
      TableName: "Ranking",
      FilterExpression: "#username = :username",
      ProjectionExpression: "#username, Score, #duration",
      ExpressionAttributeNames: {
          "#username": "Username",
          "#duration": "Duration",          
      },
      ExpressionAttributeValues: {
            ":username": {
              S: 'Alberto'
            },
      }
    };    
    
    ddb.scan(params, function (err, data) {
      if (err) {
        callback(null,  err)  
      } else {
        callback(null,  data.Items)  
      }
    });

};
Related