bokunonikki.net
JP / EN

AWS SDK3 nodejs エラー dynamodb cannot read property 0 of u

Sat Oct 23, 2021
Sat Oct 23, 2021

最近、AWS SDK nodejsをバージョン3へアップデートしているのですが、そこでエラーに遭遇したのでメモしておきます。

v2ではDynamoDBの処理はこのように書いていました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var params = {
  TableName: 'Table',
  IndexName: 'Index',
  KeyConditionExpression: 'HashKey = :hkey and RangeKey > :rkey',
  ExpressionAttributeValues: {
    ':hkey': 'key',
    ':rkey': 2015
  }
};

var documentClient = new AWS.DynamoDB.DocumentClient();

documentClient.query(params, function(err, data) {
   if (err) console.log(err);
   else

v3でも対して変わらないだろうと思って、こんなふうに書いたらエラーに遭遇。

TypeError: Cannot read property '0' of undefined

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const params = {
  TableName: 'Table',
  IndexName: 'Index',
  KeyConditionExpression: 'HashKey = :hkey and RangeKey > :rkey',
  ExpressionAttributeValues: {
    ':hkey': 'key',
    ':rkey': 2015
  }
};
const command = new QueryCommand(params);
const data = await dynamoDBClient.send(command);

どうもv3からは値を渡すときは、タイプを指定してオブジェクトを渡す必要があるみたいです。

なので、このように修正します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const params = {
  TableName: 'Table',
  IndexName: 'Index',
  KeyConditionExpression: 'HashKey = :hkey and RangeKey > :rkey',
  ExpressionAttributeValues: {
    ':hkey': { S: 'key'},
    ':rkey': { N: '2015'}
  }
};
const command = new QueryCommand(params);
const data = await dynamoDBClient.send(command);

参考リンク

See Also