Jatin Mehrotra
Jatin Mehrotra

Reputation: 11634

Why does Delete method of Amazon DynamoDB not return deleted result?

I am creating an express api for delete operation, after successful deletion of item, i want that deleted item to be shown as response, the item is getting deleted from the table but the API gives empty object {} as response when ran from CURL command, i am following these docs from aws.

here is my code

router.delete('/delete/:id',function(req, res, next) {
  
  const params = {
    TableName: 'Notes',
    Key: {
      id: req.params.id,
    },
  };

  dynamoDb.delete(params, function (error,data) {
    if (error) {
      console.log(error);
      res.status(400).json({ error: 'Could not update user' });
    }
    res.status(200).json(data);
  });
})

curl command

curl -H "Content-Type: application/json" -X DELETE xxxxxxxxxxxxxxx/dev/user/delete/alexdebrie2 

Upvotes: 2

Views: 5819

Answers (2)

codersha
codersha

Reputation: 9

let params = {
    TableName: tablename,
    Key: {
      hashKey: ,`enter code here`,
      id: `enter code here`
    },
    ConditionExpression: "attribute_exists(hashKey)",// checks if item exists
    ReturnValues: 'ALL_OLD'
  };
  dynamoDB.delete(params, (error, result) => {
    if (error) {
      console.error(error);
      callback(null, {
        statusCode: error.statusCode,
        body: JSON.stringify(error),
      });
      return;
    }
    else {
      console.log(result);
    }
    // create a response
    const response = {
      isBase64Encoded: false,
      statusCode: 200,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(result),
    };
    console.log(response);
    callback(null, response);
  });
})

Upvotes: 1

Nadav Har'El
Nadav Har'El

Reputation: 13791

The DynamoDB documentation of the DeleteItem operation clearly explains that:

In addition to deleting an item, you can also return the item's attribute values in the same operation, using the ReturnValues parameter.

So a delete operation does not, by default, return the old value of the deleted item. If you want that, you need to pass the ReturnValues option to the DynamoDB request. I'm not familiar with whatever programming language you're using to implement this, but I hope you can figure this out for yourself.

Upvotes: 5

Related Questions