Search code examples
node.jsaws-lambdaamazon-dynamodbalexa-skills-kit

Scanning DynamoDB table not showing results from the column specified in ProjectionExpression


i'm trying to scan the DynamoDB tale so that i fetch only filtered items. myTable has 3 columns:L timestamp (String, PK), colors (String), userId (String)

var docClient = new AWS.DynamoDB.DocumentClient();

var params = {
    "TableName": "myTable",
    "ProjectionExpression": "colors, userId",
    "ExpressionAttributeValues": {":val": userId},
    "FilterExpression": "userId = :val"

};

console.log("Scanning table.");
docClient.scan((params), function(err,data){

    if (err) console.log(err, err.stack); 
    else console.log(data); //success response
});

2018-05-22T08:04:21.395Z baac6d92-5d96-11e8-ae78-bd04c275acf5 Scanning table. 2018-05-22T08:04:21.672Z baac6d92-5d96-11e8-ae78-bd04c275acf5 { Items: [ { userId: 'amzn1.ask.account.XYZ' } ], Count: 1, ScannedCount: 2 }

As a result i'm only getting value(s) from userId column. The column 'colors' is completely ignored.

What am i doing wrong?


Solution

  • Setting ProjectionExpression attributes in ExpressionAttributeNames. Check out the following snippet

    var docClient = new AWS.DynamoDB.DocumentClient();
    
     var params = {
      ExpressionAttributeNames: {
       "#colors": "colors", 
       "#userId": "userId"
      }, 
      ExpressionAttributeValues: {
        ":val": userId
      }, 
      FilterExpression: "userId = :val", 
      ProjectionExpression: "#colors, #userId", 
      TableName: "myTable"
     };
    
    console.log("Scanning table."); 
    
    docClient.scan(params, function(err, data) {
        if (err) console.log(err, err.stack); 
        else console.log(data); //success response
    });
    

    Note the # and : must be present on ExpressionAttributeNames and ExpressionAttributeValues, respectively.