【问题标题】:Trouble making a Query of DynamoDB with Lambda (Node.js)使用 Lambda (Node.js) 查询 DynamoDB 时遇到问题
【发布时间】:2020-03-29 01:16:24
【问题描述】:

我想进行查询以返回具有特定用户 ID 的所有条目,在本例中为 Will666。我有一个 primaryKey 和一个 sortKey。

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'eu-west-2', apiVersion: '2012-08-10'});

exports.handler =  (event, context, callback) => {


    const params = {

        TableName: "signalepisodes",
        KeyConditionExpression: "userID = :a",
        ExpressionAttributeValues: {
        ":a": "Will666"
    }

    };
    dynamodb.query(params, function(err, data){
          if (err) {
            console.log(err);
            callback(err);
        } else {
            console.log(data);
              const items = data.Items.map(
                (dataField) => {
                  return { userID: dataField.userID.S, uploadDate: dataField.uploadDate.N, epTitle: dataField.epTitle.S };
              } 

                );

            callback(null, items);

        }
    });
    };

我在测试时收到此错误消息。我猜我的语法是错误的,但我无法解决。

"errorType": "MultipleValidationErrors",

我的 dynamoDB 表如下所示:

【问题讨论】:

    标签: amazon-web-services amazon-dynamodb


    【解决方案1】:

    DynamoDB SDK 有两种类型的客户端:

    1. 低级客户端:new AWS.DynamoDB(...)
    2. 高级客户:new AWS.DynamoDB.DocumentClient(...)

    您当前正在使用 #1,但您正在为查询提供属性,就好像您使用的是文档客户端 #2。

    所以,要么切换到 DocumentClient,继续使用:

    {":a": "Will666"}
    

    或坚持使用低级客户端并更改您的属性以指示值类型,例如:

    {":a": {"S": "Will666"}}
    

    我推荐DocumentClient,因为它显着简化了数据的编组和解组。

    我还建议将您的代码从旧的回调样式异步代码更新为新的基于 Promise 的选项。例如,像这样:

    exports.handler = async (event, context) => {
        const params = {
            TableName: "signalepisodes",
            KeyConditionExpression: "userID = :a",
            ExpressionAttributeValues: { ":a": "Will666" }
        };
    
        const items = await dynamodb.query(params).promise();
    
        for (const item of items) {
            console.log('Item:', item);
        }
    
        return items;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 2016-05-20
      • 1970-01-01
      • 2013-03-10
      相关资源
      最近更新 更多