NodeJS lambda dynamoDB putItem 仅当主排序键不同时 [英] NodeJS lambda dynamoDB putItem only if primary sort key is different

查看:33
本文介绍了NodeJS lambda dynamoDB putItem 仅当主排序键不同时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个 lambda 函数,该函数将存储有关不同用户的信息.我有一个属性,userID 作为我的主分区键,storedObject 作为我的主排序键.当我使用 PutItem 时,我希望它只添加存储对象属性中尚不存在的项目.

I'm working on a lambda function that will store information about different users. I have an atribute, userID as my primary partition key, and storedObject as my primary sort key. When I use PutItem, I want it to only add the item if it doesn't already exist in the storedObject attribute.

这是我的代码

    var params = {
        TableName: 'TrackItDB',
        Item: {
          'userID' : {S: currentUser},
          'storedObject' : {S: itemName},
          'lenderPerson' : {S: personName},
          'objectStatus' : {S: 'lent'},
          'transactionDate': {S: date},
        }
      };
....
const checkIfItemIsStoredParams = {
        Key: {
        "userID" : {
            S: currentUser
        },
        "storedObject" : {
            S: itemName
        }
    },
        TableName: "TrackItDB"
    };
.....
  dynamodb.getItem(checkIfItemIsStoredParams, function(err, data) {

        if (!data) { 
            // no match, add the item
            console.log('Item did not exist, storing to DB');
            console.log(params);
            return dynamodb.putItem(params, function(err, data) {
                if (err) {
                    console.log("Error", err);
                } else {
                    console.log("Success", data);
                }
               });
        }       
        else {
          console.log('Get item succeeded', data);   
              }
        } 
        });

我遇到的问题是,即使没有数据,它也总是向控制台输出 Get Item successed.我已经尝试过 if (data) 和 if (!data) 并且都返回 get item 成功,即使没有返回数据.

The problem I'm having is that it always outputs Get Item succeeded to the console even if there is no data. I've tried both if (data) and if (!data) and both return the get item succeeded even when there is no data returned.

推荐答案

getItem 返回一个数组,即使它没有找到您要查找的项目.因此,您的条件语句将始终为真,因为您正在检查数据是否为空/未定义.您应该检查数据的长度:

getItem returns an array even if it doesn't find the item you're looking for. Therefore, your conditional statement will always be truthy since you're checking for whether data is null/undefined. You should instead check for the length of data:

if (!data.length) { // item doesn't exit
    // put new item
}

另一种解决方案是通过对 DynamoDB 进行一次调用而不是两次调用来简化您尝试执行的操作.如果您担心性能或 AWS 使用成本,这可能是个好主意.putItem 具有参数 ConditionExpression,它允许您根据您指定的条件细粒度控制应更新哪些项目.

An alternative solution would be to simplify what you're trying to do by making a single call to DynamoDB instead of two. This might be a good idea if you're worried about performance or AWS usage costs. putItem has the parameter ConditionExpression which allows you to have fine-grain control over which items should be updated based on conditions that you specify.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html

对于您的情况,它可能看起来像这样:

For your case it might look something like this:

var params = {
    TableName: 'TrackItDB',
    Item: {
      'userID' : {S: currentUser},
      'storedObject' : {S: itemName},
      'lenderPerson' : {S: personName},
      'objectStatus' : {S: 'lent'},
      'transactionDate': {S: date},
    },
    ConditionExpression: 'attribute_not_exists(storedObject)'
};

dynamodb.putItem(params, function(err, data) {
    if (err) {
        console.log("Error", err);
    } else {
        console.log("Success", data);
    }
});

这篇关于NodeJS lambda dynamoDB putItem 仅当主排序键不同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆