如何根据数组中的值扫描dynamoDB?

时间:2018-05-17 12:06:25

标签: node.js amazon-dynamodb

这是我的代码,其中我有一个数组中的值列表。我需要从项目表中获取与数组中的id匹配的所有项目。

            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);

                }
            });

但是我没有得到正确的结果。

1 个答案:

答案 0 :(得分:1)

选项1 - 静态: -

如果您事先了解所有值,请构建FilterExpression,如下所述: -

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

    }
};

选项2 - 动态: -

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);
        }
    }
}