在使用 AWS.DynamoDB.DocumentClient 更新第二个表之前,如何使用事务检查一个表中是否存在某个项目?

Sus*_*san 1 javascript amazon-dynamodb

我是 DynamoDB 的新手。我有一个名为“kids-profiles”的 DynamoDB 表,它列出了用户的子配置文件(主分区键“userId”,主排序键“childId”)。我有一个名为“kids-tasks”的第二个表,它列出了孩子的任务(主分区键“childId”,主排序键“taskId”)。仅当“childId”存在于“kids-profiles”表中时,我才想以原子方式将一个项目添加到“kids-tasks”表中。

我正在尝试使用 AWS.DynamoDB.DocumentClient 类 ( https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html )的 transactWrite 方法来实现这一点,但我不能让它工作。首先,当我尝试向 TransactionItems 添加 ConditionCheck 时,它显示“TransactItems 只能包含 Check、Put、Update 或 Delete 之一”。所以我将“ConditionCheck”改为“Check”,假设这是正确的,即使文档中没有提到它。其次,当我让它执行时,它会将任务添加到 'kids-tasks' 表中,无论 'childId' 是否存在于 'kids-profiles' 表中。

    const params = {
        TransactItems: [ 
            {
                Check: {
                    TableName: "kids-profiles",
                    Key: {
                        userId:   userId,
                        childId:  childId,
                    },
                    ConditionExpression: "attribute_exists(childId)",
                },
                Put: {
                    TableName: "kids-tasks",
                    Item: {
                        childId:  childId,
                        taskId:   uuid.v1(),
                        title:    title,
                    }
                }
            }
        ]
    };

    try 
    {
        await dynamoDb.transactWrite(params).promise();
        console.log("Success!");
    } 
    catch (error) 
    {
        console.log("Error");
    }
Run Code Online (Sandbox Code Playgroud)

小智 8

Divide objects into individual Operations.

 const params = {
     TransactItems: [ 
         {
            ConditionCheck: {
                ...
            },
+        }, // <------ !!!!!
+        {
             Put: {
                ...
         }
     ]
 };
Run Code Online (Sandbox Code Playgroud)