node.js AWS dynamodb updateItem

新手上路,请多包涵

有没有办法用updateItem实现以下几点:

  1. 如果 DynamoDB 中不存在属性,则添加属性
  2. 如果 DynamoDB 中存在属性,则更新属性
  3. 如果这些属性不包含在参数中,则将这些属性保持原样。

这是一个示例: 这是 DynamoDB 中的对象:

 {
    id: "1234",
    variable1: "hello",
    variable2: "world"
}

这是我希望更新的输入:

 {
    id: "1234",
    variable1: "hello2",
    variable23: "dog"  // the variable name "variable23" could be anything
}

这是我想要实现的 DynamoDB 中的更新项目:

 {
    id: "1234",
    variable1: "hello2",
    variable2: "world",
    variable23: "dog"
}

“variable23”可以是任何变量名作为输入。

我使用 node.js

原文由 Pano 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 617
2 个回答

这正是 AWS.DynamoDB.DocumentClient 的 update 方法所做的。

对于 AWS SDK for JavaScript in Node.js, 这里 已经有一个示例代码说明如何使用 update 方法。

例如:

 'use strict';

const aws = require('aws-sdk');

// It is recommended that we instantiate AWS clients outside the scope of the handler
// to take advantage of connection re-use.
const docClient = new aws.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    const params = {
        TableName: "MYTABLE",
        Key: {
            "id": "1"
        },
        UpdateExpression: "set variable1 = :x, #MyVariable = :y",
        ExpressionAttributeNames: {
            "#MyVariable": "variable23"
        },
        ExpressionAttributeValues: {
            ":x": "hello2",
            ":y": "dog"
        }
    };

    docClient.update(params, function(err, data) {
        if (err) console.log(err);
        else console.log(data);
    });
};

原文由 Khalid T. 发布,翻译遵循 CC BY-SA 3.0 许可协议

我认为有些例子有点令人困惑。如果我有下表列

ID  | Name | Age

我想更新 Name 属性并保持 Age 属性不变。

 const updateName = async () => {
  const aws = require('aws-sdk');
  const docClient = new aws.DynamoDB.DocumentClient();

  const newName = 'Bob';

  const params = {
    TableName: 'myTable',
    Key: {
      ID: 'myId',
    },
    UpdateExpression: 'set Name = :r',
    ExpressionAttributeValues: {
      ':r': newName,
    },
  };

  await docClient.update(params).promise();
}

updateName();

这似乎更简单一些。

原文由 thedanotto 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题