dynamodb.put().promise() not returning the put object

dynamodb put if not exists
dynamodb async/await
aws lambda promise
dynamodb getitem nodejs
aws sdk dynamodb
dynamodb put request
aws sdk promise
s3 putobject promise

I am trying to make use of the async/await functionality with regard to aws and dynamo db. Below is an example of how to put an object pre asyn await, as you can see in the callback you have access to data which contains the put object. However in the second block of code which uses async and promise the result is an empty object, any thoughts?

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html

Non Promise Version

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

var table = "Movies";

var year = 2015;
var title = "The Big New Movie";

var params = {
    TableName:table,
    Item:{
        "year": year,
        "title": title,
        "info":{
            "plot": "Nothing happens at all.",
            "rating": 0
        }
    }
};

console.log("Adding a new item...");
docClient.put(params, function(err, data) {
    if (err) {
        console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("Added item:", JSON.stringify(data, null, 2));
    }
});

Promise async Version - assume the wrapping function is marked async

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

var table = "Movies";

var year = 2015;
var title = "The Big New Movie";

var params = {
    TableName:table,
    Item:{
        "year": year,
        "title": title,
        "info":{
            "plot": "Nothing happens at all.",
            "rating": 0
        }
    }
};
const result: any = await dynamoDb.put(params).promise()
console.log(result) 

According to the doc you have to use ReturnValues if you want something back.

AWS SDK put is returning empty for DynamoDB � Issue #1904 � aws , AWS SDK put is returning empty for DynamoDB #1904. Closed Item: { id: uuid() , firstName: firstName, lastName: lastName } } return Observable.fromPromise( database.put(params).promise()) } By default, DynamoDB::PutItem (and, by extension, the DocumentClient's put method) returns no data. The item to be put is identified by an Item subelement: Item - A map of attributes and their values. Each entry in this map consists of an attribute name and an attribute value. Attribute values must not be null; string and binary type attributes must have lengths greater than zero; and set type attributes must not be empty.

When you're using promises, you should handle the returned promise object using .then() and .catch(). If you take a look at the documentation, your request should look like this:

dynamoDb.put(params).promise()
  .then(function(data) {
    console.log(data);
  })
  .catch(function(err) {
    console.log(err);
  });

This will also help you see if you are getting any error (same idea as surrounding an await with try/catch, but clearer syntax)

Using JavaScript Promises, Request object is returned when a service operation is called without a callback function. You can call the request's send method to make the service call. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values. You can return the item's attribute values in the same operation, using the ReturnValues parameter.

I have tried ReturnValues: 'ALL_OLD' but in async await it has no result.

Here is a part of code:

const answersParams = {
          TableName: ANSWERS_TABLE,
          Item: {
            answersId,
            answers,
            userId,
            quizId,
          },
          ReturnValues: 'ALL_OLD',
        };

        try {
          const createdAnswres = await db.put(answersParams).promise();

          return {
            statusCode: 201,
            body: JSON.stringify(createdAnswres && createdAnswres.Item),
          };
        } catch (error) {
          return {
            statusCode: 500,
            body: 'failed to save user answers',
          };
        }
      }
    

So I had to add another request to db:

const createdAnswres = await db.get({
              TableName: ANSWERS_TABLE,
              Key: { answersId },
            })
            .promise();
    

Class: AWS.DynamoDB.DocumentClient — AWS SDK for JavaScript, The DocumentClient , does not accept AttributeValue s in favor of native JavaScript types. Request. Returns a set of attributes for the item with the given primary key by getItem() . put(params, callback) ⇒ AWS.Request. Creates a new item,� Items are the key building block in DynamoDB. In this lesson, we're going to learn the basics of inserting and retrieving items with DynamoDB. We'll create a Users table with a simple primary key of Username.

How to get AWS SDK for Node.js to return Promises to use with , Supposedly, AWS SDK for JavaScript does not support Promises be doing our best to use async/await functions, and to use functions that return Promise objects, return await new Promise((resolve, reject) => { dynamoDb.put(params, (error, data) => { if (error) After this method is called, promise() will exist on all AWS. Instantiate PutItemRequest object, this object will send the client request to dynamoDB. Set name of the table where items will be inserted. In our case JOB. Set return consumed capacity as TOTAL, this returns aggregate consumed capacity. Set return values as ALL_OLD, this returns old item values in case of item is already present.

Chapter 3: Asynchronous work is easy, we Promise(), res) return res }) .catch((saveError) => { #6 console.log(`Oops, order is not saved :(` #2 Put the new pizza order in the DynamoDB table. pzwr yvp cwnr vr sub vr krq Item jteobc khq tks gapnsis vr kgr DocumentClient.put hdmeto. new Api() api.get('/', request => { return new Promise(resolve => { #1 setTimeout(() => { #2� Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more

Using the DynamoDB Document Client, Putting an Item in a Table. Create a Node.js module with the file name ddbdoc_put.js . Be sure to configure the SDK as previously shown. To access DynamoDB� The SDK for Java also provides an object persistence model, allowing you to map your client-side classes to DynamoDB tables.

Comments
  • What is : any ?
  • its typescript, just means that result can be of any type
  • Maybe you should update the tags
  • Are you catching the errors ?
  • You likely mean docClient.put in the async example, instead of dynamoDb.put? If so, would you please fix the typo
  • hmm yes that does seem to make sense, weird how the non promise object does seem to return the full object in the callback regardless of whether you have set this value, TBH i dont really need a response but it bugged me the behavior appeared different and wanted to make sure I wasnt missing anything / doing anything silly. Thanks for looking into it, ill mark this as the correct answer
  • presumably clearer syntax is a matter of opinion and shouldn't affect the behavior? No error is being thrown, the object is being created in the database but the response is an empty object rather than the put object
  • Yupe shouldn't affect behavior, but handling the promise success/error in the correct way is not an opinion. It's successful and the object returned is empty, even when using .then()? That can't be possible...
  • According to this aws.amazon.com/blogs/compute/… both methods are "corret" ways of handling promise success and error. Anyway i tried it using .then().catch() and behaviour is the same, empty response object, weird