Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS DynamoDb DocumentClient - Creating a batchWrite from an array of Items - node.js

I'm trying to perform a batchWrite operation using DynamoDB's DocumentClient from an array of items (JSON)

This is my code:

var items = [];

for (i = 0; i < orders.length; i++) {
    var ord = orders[i]; //a simple json object
    var item = { 
        'PutRequest': { 
            'Item' : ord[i] 
        } 
    };

    items.push(item);
 }


var params = {
    RequestItems: {
        'my_table_name': items
    }
};

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

docClient.batchWrite(params, function(err, data) {

    if (err) {
        console.log('There was a problem putting the items in the table');
        context.fail(err);
    } 
    else {
        console.log('Items updated in table');
        context.done();
    }
});

I am getting the following error:

{"errorMessage":"Missing required key 'Item' in        
 params.RequestItems['my_table_name']
 [0].PutRequest","errorType":"MissingRequiredParameter"...

I have looked at the documentation but I can't understand what I am doing wrong.

like image 579
Zigglzworth Avatar asked Jan 05 '16 17:01

Zigglzworth


1 Answers

Here is the correct way to do it:

function batchWrite(arrayOf25) {

 //25 is as many as you can write in one time

  var itemsArray = [];

  for (i = 0; i < arrayOf25.length; i++) {

    var someItem = arrayOf25[i];
    var item = {
                PutRequest: {
                 Item: someItem
                }
             };


    if (item) {
      itemsArray.push(item);
    }

 }


  var params = {
      RequestItems: { 
        'my_table_name': itemsArray
      }
    };

    //var AWS = require('aws-sdk'); //These should be added at the top
    //var docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});

    docClient.batchWrite(params, function(err, data) {

      if (err) {
          console.log(err); 
      } 
      else  {

          console.log('Added ' + itemsArray.length + ' items to DynamoDB');

      }   


    });


}
like image 58
Zigglzworth Avatar answered Oct 27 '22 18:10

Zigglzworth