1

How can I delete an item from a DynamoDB database from a Lambda function. I know how to put and item. Here is working code:

dynamo.putItem({
            "TableName": "Table",
            "Item": item
        }, function(err, data) {
            if (err) {
                console.log("Failure: " + err);
                context.succeed("Failure!");
                context.done();
            } else {
                console.log("Success!");
                context.succeed("Success!");
                context.done();
            }
        });

3 Answers 3

3

this works for me... omitting the lambda boilerplate stuff...

    var tableName = "Users"
dynamodb.deleteItem({
    "TableName": tableName, 
    "Key" : {
        "UserId": event.UserId
    }
}, function (err, data) {
    if (err) {
        context.fail('FAIL:  Error deleting item from dynamodb - ' + err);
    }
    else {
        console.log("DEBUG:  deleteItem worked. ");
        context.succeed(data);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Correction to the code above, this is working :

var tableName = "Users";
dynamodb.deleteItem({
    "TableName": tableName, 
    "Key" : {
        "UserId": {
            "N" : event.userId.toString()
         }
    }
}, function (err, data) {
    if (err) {
        context.fail('FAIL:  Error deleting item from dynamodb - ' + err);
    } else {
        console.log("DEBUG:  deleteItem worked. ");
        context.succeed(data);
    }
});

Comments

0
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
  const connectionId = event.requestContext.connectionId;
  deleteConnectionId(connectionId).then(() => {
    callback(null, { statusCode: 200 , message: 'userId deleted'});
  });
};


function deleteConnectionId(connectionId) {
  return ddb
    .delete({ TableName: 'your table name', 
        Key: {
            userId : connectionId.toString() // userId is my PK in this case
         }
    } )
    .promise();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.