1

I have a simple logic where I want to INSERT record in the table using AWS.DynamoDB.DocumentClient. Below is code which I am using. Here, I am noticing that .put is updating the record and not sure why.

While checking the logs in CW, I am not seeing any error so not sure what am I missing here.

Code:

async addEvent(incomingModel: MyModel): Promise <MyModel> {
    const dynamoModel: MyModel = {
        fieldOne: incomingModel.fieldOne,
        fieldTwo: incomingModel.fieldTwo,
        "One#two#three": `${incomingModel.one}#${incomingModel.two}#${incomingModel.three}`,
        fieldThree: incomingModel.fieldThree,
        fieldFour: incomingModel.fieldFour,
    };

    var params = {
        TableName: 'Table',
        Item: dynamoModel,
    };

    return this.documentClient
        .put(params)
        .then((data) => {
            this.logger.debug(
                "Response received from Dynamo after adding an incomingModel",
                data,
                this.constructor.name,
            );

            return data as MyModel;
        })
        .catch((error) => {
            const errorMessage = JSON.stringify(error);
            this.logger.error(
                `Error creating incomingModel with body of ${errorMessage}`,
                error,
                this.constructor.name,
            );
            throw error;
        });
}
4

2 回答 2

4

这是put操作的预期行为。从文档(强调我的):

创建新项目,或用新项目替换旧项目。如果指定表中已经存在与新项具有相同主键的项,则新项完全替换现有项。

于 2020-09-02T17:01:45.113 回答
0

正如 Seth 所提到的,这是 DynamoDb 的默认行为。

避免更新的方法是使用“ConditionExpression”。在我的示例中,我将“PK”命名为 HashKey,将“SK”命名为 RangeKey:

async function put(Item, TableName){
    const params = {
        TableName,
        Item,
        ExpressionAttributeNames : {
            '#pk' : 'PK',
            '#sk' : 'SK',
        },
        ConditionExpression : 'attribute_not_exists(#pk) AND attribute_not_exists(#sk)',
    };
    
    const result = await documentClient.put(params).promise();
    
    // ... do the rest....

}

如果该项目已经存在(两个键都匹配),则交易将失败,并给出"ConditionalCheckFailedException: The conditional request failed"

我希望这会有用!

于 2021-04-05T00:02:50.467 回答