Home > OS >  query on dynamodb through lambda using pk and sk returns undefined
query on dynamodb through lambda using pk and sk returns undefined

Time:10-02

I have a lambda function that makes a call to the dynamodb table using pk and sk. For some reason I am getting the return data as undefined. Upon checking the cloudwatch logs I see the below error messages. What could be the typo I am doing here?

2021-10-01T00:15:03.104Z cdd7201f-0c95-4283-9257-c07324998896 INFO BOL Data: undefined

2021-10-01T00:15:03.124Z cdd7201f-0c95-4283-9257-c07324998896 INFO BOL Error: TypeError: Cannot read property 'PK' of undefined at getUserById (/var/task/getUserById.js:16:27) at processTicksAndRejections (internal/process/task_queues.js:95:5)

Here is the lambda code the error is referring to -

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

async function getUserById(userId) {
    console.log('USERID:',userId);
    const params = {
        TableName:"Bol",
        KeyConditionExpression: 'PK = :hashKey and SK = :sortKey',
        ExpressionAttributeValues: {
            ':hashKey': userId,
            ':sortKey': 'USER'
        }
    };
    try {
        const { Item } = await docClient.query(params).promise();
        console.log('BOL Data:',Item);
        return { id: Item.PK, name: Item.Data.displayName };
    } catch(err) {
        console.log("BOL Error: ", err);
    }
 }
 
 module.exports = getUserById;

Below is the data I am supposed to receive on lambda - enter image description here

CodePudding user response:

The PK should be like this:

 const params = {
        TableName:"Bol",
        KeyConditionExpression: 'PK = :hashKey and SK = :sortKey',
        ExpressionAttributeValues: {
            ':hashKey': `USER-${userId}`,
            ':sortKey': 'USER'
        }
    };

CodePudding user response:

Its the way you are Initialization the Item by default dynamodb sends response

you can try using the below methods to get the objects

 try {
        const Item  = await docClient.query(params).promise();
        Item.Items.forEach(function(item) {
            let buffer=item.Data " -- " item.PK;
           console.log("buffer ",buffer)
        });
        
    } catch(err) {
        console.log("BOL Error: ", err);
    }

There's are multiple ways you can get the favourable response refer below:

Making Requests with the Document Client

Formatting DynamoDB data to normal JSON in AWS Lambda

  • Related