How to fetch/scan all items from `AWS dynamodb` using node.js

前端 未结 11 2804
清酒与你
清酒与你 2020-11-30 00:19

How to fetch/scan all items from AWS dynamodb using node.js. I am posting my code here.

var docClient = new aws.DynamoDB.DocumentCl         


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 01:14

    Using Promises and async

    const aws = require('aws-sdk');
    aws.config.update({ region: 'us-east-1' });
    const documentClient = new aws.DynamoDB.DocumentClient();
    
    const scanAll = async (params) => {
      let lastEvaluatedKey = 'dummy'; // string must not be empty
      const itemsAll = [];
      while (lastEvaluatedKey) {
        const data = await documentClient.scan(params).promise();
        itemsAll.push(...data.Items);
        lastEvaluatedKey = data.LastEvaluatedKey;
        if (lastEvaluatedKey) {
          params.ExclusiveStartKey = lastEvaluatedKey;
        }
      }
      return itemsAll;
    }
    

    Use like this

    const itemsAll = scanAll(params);
    

    The code is the same for query (just replace scan with query)

提交回复
热议问题