如何检查emaiID在dynamodb中是否存在?

时间:2019-04-24 08:54:26

标签: amazon-dynamodb

am使用节点js进行lambda函数。我需要检查dynamo数据库中是否存在emailID ...如果emailID存在,则应提示用户已存在emailid,否则应将值存储在dynamo数据库中。...

EmailID是排序键 客户名称是主键

我该怎么做..

下面是我的代码:

var doc = require('aws-sdk');
var dynamodb = new doc.DynamoDB()

var tableName = "Testing";

exports.handler = (event, context, callback) => {



var EmailID = event.EmailID; // or any other var which is having emaiID

console.log(event)

 var params = {
            TableName: "Testing",
            Key: { EmailID : "abc@gmail.com",
                   CustomerName : "ABC"},
            AttributeUpdates: {
                verified: {
                    Action: "PUT",
                    Value: true
                }
            }
        };

        // Update the user.
        dynamodb.update(params, function(err, data)
        {
            if (err)
            {
                console.log(JSON.stringify(err));
                context.fail(JSON.stringify(err));
                return;
            }
            context.succeed("User successfully updated.");
        });

putItem

var AWS = require('aws-sdk');

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


exports.handler = (event, context, callback) => {
    // TODO implement

   var tableName = "Testing";

    console.log(event.EmailID)

    var parms = {
        TableName : tableName,
       Item : {
            "EmailID" : event.EmailID,
            "CustomerName" : event.CustomerName,
            "PersonName" : event.PersonName,
            "EmailSent" : event.EmailSent,
             "Password" : event.Password
        }
    };
docClient.put(parms, function(err, data)
{
   if (err){
       callback(err)
   }
   else
   {
       callback(null,"Successfully updated data!!!")
   }
})
};

1 个答案:

答案 0 :(得分:0)

要实现此目的,我将使用Put操作并使用“ exists”参数。将其设置为false将确保如果项已存在则放置操作将失败。如果没有匹配项,则放置将插入记录。

有关如何在javascript中使用此操作的更多详细信息,请查看文档: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#putItem-property

因此,在放置示例中,您可以将以下内容添加到参数中:

var AWS = require('aws-sdk');

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


exports.handler = (event, context, callback) => {
    // TODO implement

    var tableName = "Testing";

    console.log(event.EmailID)

    var parms = {
        TableName: tableName,
        Item: {
            "EmailID": event.EmailID,
            "CustomerName": event.CustomerName,
            "PersonName": event.PersonName,
            "EmailSent": event.EmailSent,
            "Password": event.Password
        },
        ConditionExpression: "attribute_not_exists(EmailID)"
    };
    docClient.put(parms, function (err, data) {
        if (err) {
            callback(err)
        }
        else {
            callback(null, "Successfully updated data!!!")
        }
    })
};