【问题标题】:Using aws sdk for javascript to write condition expressoins in DynamoDB when a new attribute is greater than the origin attribute当新属性大于原始属性时,使用 aws sdk for javascript 在 DynamoDB 中编写条件表达式
【发布时间】:2018-08-08 14:52:07
【问题描述】:

当新属性大于原始属性时,我想更新 DynamoDB 中的项目。

例如,下面给出的示例 dynamodb 结构

id(primary key)  value   count
---------------  -----   -----
a                1       10
b                2       10

-------------------------------------------
// When input this item, I wish not to update
-------------------------------------------
a                5       9 (9 is smaller than 10)

-------------------------------------------
// When input this item, I wish to update
-------------------------------------------
b                5       15 (15 is greater than 10)

这是我的代码:

const DynamoDB = require('aws-sdk').DynamoDB;
const db = new DynamoDB.DocumentClient();
const TableName = "sample_table";

function update(id, value, count)
{
    return db.update({
        TableName,
        Key: { 
            id
        },
        UpdateExpression: "SET #value = :value, #count = :count",
        ConditionExpression: "#count > :count",
        ExpressionAttributeNames:
        {
            "#value": "value",
            "#count": "count"
        },
        ExpressionAttributeValues:
        {
            ":value": value,
            ":count": count
        }
    }).promise();
}
update("a", 5, 9);
update("b", 5, 15);

但是在我运行这段代码之后,它会抛出错误

UnhandledPromiseRejectionWarning: ConditionalCheckFailedException: The 条件请求失败

如何使用 ConditionExpression 参数来满足我的需要,我该如何解决?

【问题讨论】:

    标签: node.js amazon-web-services amazon-dynamodb


    【解决方案1】:

    这是预期的。因为第一次更新 - update("a", 5, 9) 将被拒绝,因为它不能满足您的条件。 DynamoDB rejects 条件表达式失败时的承诺。你应该在你的代码中处理这个。

    可能是这样的:

    update('a', 5, 9)
    .then(data => {
        console.log(data);
    })
    .catch((err) => {
        if (err.code === 'ConditionalCheckFailedException') {
            return 'Ok I know this';
        }
        throw err;
    });
    

    【讨论】:

    • 谢谢!终于找到问题了:如果条件表达式计算为假,DynamoDB返回如下错误信息:条件请求失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2011-11-01
    • 2014-02-21
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多