如何用DynamoDB调用单项?

How to call single item with DynamoDB?

我正在尝试调用 getItem 到 DynamoDB。我正在使用文档中的代码示例,但是,我得到的只是 null

我的 item123id 附加了几行,我想在控制台日志中检索它们。

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({ region: 'eu-central-1' });

exports.handler = async (event) => {

  // Create the DynamoDB service object
  ddb = new AWS.DynamoDB({ apiVersion: '2012-10-08' });

  var params = {
    TableName: 'table',
    Key: {
      'id': { N: '123' },
    }
  };

  // Call DynamoDB to read the item from the table
  ddb.getItem(params, function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data.Item);
    }
  });

};

您的 getItems 调用是异步的,并且您的 Lambda 函数在您的 dynamodb 调用 returns 之前完成,因此没有记录任何内容。您实际的数据库调用可能工作正常。

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html

这是我的 lambda 函数的示例(请将执行环境更改为 Node.js 6.10 和 table 以及 ID 名称和值)。这有效,并记录了一些信息。请尝试...

'use strict';

const aws = require('aws-sdk'); 
const dbCon = new aws.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = (event, context, callback) => {
    var params = {
        TableName: "trans",
        Key: {
            "transid": {"S": "Bk6ZQF0Q7"}
        }
    };

    console.log("Attempting a call getitem...");

    dbCon.getItem(params, function (err, data) {
        if (err) {
            console.error("Unable to getItem. Error JSON:", JSON.stringify(err, null, 2));
        }
        else {
            console.log("getItem succeeded:", JSON.stringify(data, null, 2));
        }
    });

    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    }; 

    callback(null, response); 
};
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({region: 'REGION'});
exports.handler = (event, context, callback) => { 
// Create the DynamoDB service object
ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'});

var params = {
  TableName: 'TABLE',
  Key: {
    'KEY_NAME' : {N: '123'},
  },
  ProjectionExpression: 'ATTRIBUTE_NAME'
};

// Call DynamoDB to read the item from the table

ddb.getItem(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
}

这是我的 lambda 示例,您可以尝试一下。