0

here is my code where i have a list of values in an array. I need to fetch all the projects from project table which matches the id's in the array.

            var arr=[];
            for(var index in data.Items){
                if(data.Items[index].hasOwnProperty('projectId'))
                arr.push(data.Items[index].projectId);
            };

            var params = {
                TableName: 'projects',
                FilterExpression: 'id IN (:id)',
                ExpressionAttributeValues: {
                    ':id': arr
                }

            };

            dynamodbclient.scan(params, function (err, docs) {
                if (err) {
                    console.log("Error", err);
                } else {
                    console.log("Success");
                    callback(err, docs.Items);

                }
            });

However i am not getting the proper results.

1 Answer 1

1

Option 1 - Static :-

If you know all the values its count upfront, please construct the FilterExpression as mentioned below:-

var params = {
    TableName : "projects",
    FilterExpression : "id IN (:id1, :id2)",
    ExpressionAttributeValues : {
        ":id1" : "id val 1",
        ":id2" : "id val 2"

    }
};

Option 2 - Dynamic:-

var titleValues = ["The Big New Movie 2012", "The Big New Movie"];
var titleObject = {};
var index = 0;
titleValues.forEach(function(value) {
    index++;
    var titleKey = ":titlevalue"+index;
    titleObject[titleKey.toString()] = value;
});

var params = {
    TableName : "Movies",
    FilterExpression : "title IN ("+Object.keys(titleObject).toString()+ ")",
    ExpressionAttributeValues : titleObject
};

docClient.scan(params, onScan);

function onScan(err, data) {
    if (err) {
        console.error("Unable to scan the table. Error JSON:", JSON.stringify(
                err, null, 2));
    } else {
        // print all the movies
        console.log("Scan succeeded.");
        data.Items.forEach(function(movie) {
            console.log("Item :", JSON.stringify(movie));
        });

        // continue scanning if we have more movies
        if (typeof data.LastEvaluatedKey != "undefined") {
            console.log("Scanning for more...");
            params.ExclusiveStartKey = data.LastEvaluatedKey;
            docClient.scan(params, onScan);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.