如何使用lambda上的nodejs覆盖DynamoDB中具有不同模式但相同键的项目

时间:2017-11-15 06:14:58

标签: node.js lambda amazon-dynamodb

我正在尝试使用username覆盖DynamoDB中的项目(使用名为put的主键),如下所示:

        console.log('writing commands',existingCommands,message.username);
        var t2 = performance();
        var writeParams = {
            Item: {
                username: message.username,
                commands: existingCommands // Sorry for the confusing name, due to deepExtend existingCommands are the new commands
            },

            TableName: TableName
        };

        docClient.put(writeParams, function(err, data){
            if(err){
                console.error('error',err);
            } else {
                console.log('write result',data);
                var t3 = performance();
                console.info('delete & write performance',(t3-t2).toFixed(3));
            }
            // End function
            context.done();
        });

适用于:

  • username不存在的位置插入新项目。
  • 更新与我想要插入的项目架构相匹配的项目,例如,我正在尝试插入该项目:

    {
       "username":"ausin441062133",
        "commands": {
          "command1":"command",
          "command2":"command"
        }
    }
    

如果有一个与架构和用户名匹配的项目,它将被覆盖,即

    {
       "username":"ausin441062133",
        "commands": {
          "command1":"I will be overwritten",
          "command2":"I will be overwritten"
        }
    }

但是当有一个具有确切用户名但不同模式的项目时,它不起作用,即

    {
       "username":"ausin441062133",
        "commands": {
          "command1":"I will NOT be overwritten"
        }
    }

如果现有项与用户名匹配,我需要使用什么命令来覆盖?

1 个答案:

答案 0 :(得分:1)

最终Dmitry建议update有效,但它需要一些不同的参数而不是put这里是我的代码:

        // Step 3 write command back
        console.log('writing commands',existingCommands,message.username);
        var t2 = performance();
        var updateParams = {
            Key: {
                username: message.username
            },
            UpdateExpression: "set commands = :c",
            ExpressionAttributeValues: {
                ":c":existingCommands
            },
            ReturnValues: "UPDATED_NEW",
            TableName: TableName
        };

        docClient.update(updateParams, function(err, data){
            if(err){
                console.error('error',err);
            } else {
                console.log('write result',data);
                var t3 = performance();
                console.info('delete & write performance',(t3-t2).toFixed(3));
            }
            // End function
            context.done();
        });
相关问题