Search code examples
node.jsamazon-dynamodbaws-sdk-nodejs

DynamoDB - scan and filter map with nodejs


I'm using nodejs to scan and filter a collection in dynamodb that looks like this:

{
    "name": "teste123",
    "id": "4bbe0f00-67c3-11e7-a6be-b9c9fc540ac2",
    "clustermembers": [
        {
            "email": "teste@teste.com",
            "role": "ADMIN",
            "id": "4bbe0f00-67c3-11e7-a6be-b9c9fc540ac2"
        }
    ]
}

With the following pice of code:

var params = {
    TableName : "mytable",
    FilterExpression : "clustermembers.email = :p_email",
    ExpressionAttributeValues : {
        ":p_email": {"S": req.params.usr_email}  
    } 
};

var promiseQuery = client.scan(params).promise();

promiseQuery
    .then(function(data) {
        res.send({clusters: data.Items});
    })
    .catch(function(err) {
        console.log('ERROR -  get all clusters by user = ' + err);
        res.status(500).send('ERROR -  get all clusters by user = ' + err);
    }); 

It should return one record but I'm getting no results. What I'm missing here?

Thanks for the help!


Solution

  • The array index has to be included to get the value from List data type. Otherwise, you may need to use CONTAINS function. However, the CONTAINS function requires all the attributes in the object to map the item. In your scenario, you need to know email, id and role to use CONTAINS function.

    Note:-

    The below solution wouldn't work if you have multiple cluster members and you would like to match members present in the other occurrences in the array. In order to achieve that you need to use CONTAINS function by providing all three attributes in the object.

    var params = {
        TableName: "mytable",
        FilterExpression: "clustermembers[0].email = :emailVal",
        ExpressionAttributeValues: {
            ":emailVal": 'teste@teste.com'
        }
    };