【问题标题】:AWS SDK Working with DynamoDB and putItem won't allow me to insert without updatingAWS SDK 使用 DynamoDB 和 putItem 不允许我在不更新的情况下插入
【发布时间】:2016-07-16 04:21:56
【问题描述】:

以下是我将项目插入数据库的方式:

DynamoDB.putItemAsync({
    "TableName": tblName,
    "Item": {
        "UserId": { "S": String(obj.user_id) },
        "CampaignId": { "N": String(obj.campaign_id) },
        "Email": { "S": String(obj.email) },
        "CustomActivityNodeId": { "N": String(obj.custom_activity_node_id) }
    },
    "Expected": {
        "UserId": {
            "Exists": false
        }
    }
})

putItemAsync 调用是因为我 promisifiedbluebird 的库。我试过这样做:

{
    "Expected": {
        "UserId": {
            "Exists": false
        }
    }
}

通过我的putItem 电话,但我没有运气。我要做的就是插入记录而不更新现有记录

【问题讨论】:

  • 我遇到了类似的问题,你解决了吗?干杯

标签: node.js amazon-web-services aws-sdk


【解决方案1】:

来自PutItem API reference

要防止新项目替换现有项目,请使用 包含 attribute_not_exists 函数的条件表达式 将属性名称用作分区键 桌子。由于每条记录都必须包含该属性,因此 attribute_not_exists 函数只有在没有匹配项时才会成功 存在。

首先,确保UserId 是表的PK,然后您可以使用ConditionExpressionattribute_not_exists

DynamoDB.table('users').PutItem({}, {
    ConditionExpression: "attribute_not_exists(email)"
}).then((response) => response.json()).then((res) => {
    // [LOG] possible bug with time
})

如果电子邮件(表中的我的 pk)以前不存在,这将创建一个项目 ONLY

PS:我在 react-native 中为 dynamodb 使用了 wrapper

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 2022-07-12
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多