How can I filter the result of DynamoDB? (NodeJS / Lambda)

Issue

i’m making an API in AWS Lambda with NodeJS and DynamoDB and’m trying to get details of a specific customer or customers who comes from Colorado (state = Colorado).

Here i was trying to get all customers from Colorado.

router.get("/customers", (req, res) => {
    const params = {
      TableName: 'Customer',
      FilterExpression: "stateOrProvince = :state",
      ExpressionAttributeValues: {
        ":state": "Colorado"
      }
    };
    dynamoDb.query(params, (error, result) => {
      if (error) {
        res.status(400).json({ error: `Error fetching the ${tableName}` });
      }
      res.json(result.Items);
    });
});

Here i was trying to get details from a specific customer

router.get("/customers/:customerId", (req, res) => {
    const id = req.params.customerId
    const params = {
      TableName: 'Customer',
      FilterExpression: "customerId = :custId",
      ExpressionAttributeValues: {
        ":custId": id
      }
    };
    dynamoDb.query(params, (error, result) => {
      if (error) {
        res.status(400).json({ error: `Error fetching the ${tableName}` });
      }
      res.json(result.Items);
    });
});

Both cases i’m getting a 502 error in postman 😐

{
"message": "Internal server error"
}

Could you help me to identify what the issue is ?
I’ve read and tried differents syntaxes but I couldn’t get it to work yet
Thanks

Solution

You cannot use Query operation without using a KeyConditionExpression which you have not defined. You must at least insert the partition key for a Query.

Try below, which uses Scan instead:

router.get("/customers", (req, res) => {
    const params = {
      TableName: 'Customer',
      FilterExpression: "stateOrProvince = :state",
      ExpressionAttributeValues: {
        ":state": "Colorado"
      }
    };
    dynamoDb.scan(params, (error, result) => {
      if (error) {
        res.status(400).json({ error: `Error fetching the ${tableName}` });
      }
      res.json(result.Items);
    });
});

Or for a specific customer, set KeyConditionExpression:

router.get("/customers/:customerId", (req, res) => {
    const id = req.params.customerId
    const params = {
      TableName: 'Customer',
      KeyConditionExpression: "customerId = :custId",
      ExpressionAttributeValues: {
        ":custId": id
      }
    };
    dynamoDb.query(params, (error, result) => {
      if (error) {
        res.status(400).json({ error: `Error fetching the ${tableName}` });
      }
      res.json(result.Items);
    });
});

More info here

Answered By – Lee Hannigan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published