Search code examples
javascriptaws-lambdaamazon-dynamodbserverless-frameworkaws-sdk-nodejs

Using Lambda with Nodejs Count Some queries in Dynamo DB


After using the below to pull data from Dynamo db sucessfully

async function pullone(sessionid) {
  const params = {
    TableName: dynamodbTableName,
    Key: {
      'sessionid': sessionid
    }
  };
  return await dynamodb.get(params).promise().then((response) => {
    return response.Item
  }, (error) => {
    console.error('Do your custom error handling here. I am just gonna log it: ', error);
  });
}

Instead of 'return response.Item' i just want to return the count instead.

I tried doing count(pullone(sessionid)) but not sure if that is even a valid method. Please assist


Solution

  • Not sure if I understood your question, but:

    Since you're requesting data associated with a primary key, you'll get either 0 or 1 element in Item.

    So, if you aim to know if "you've found something or not", you can use Number(response.Item != null) and you'll get 1 in case of "something" and 0 in case of "nothing".

    If, instead, your data contains a "count" attribute, then (await pullone(sessionId)).count should work.

    Otherwise, you have to query your DB (but you'll get Items (plural) in your response) and use the length() function of the Items array you'll get in the response.