[英]How can I use transactions to check if an item exists in one table before updating a second table using AWS.DynamoDB.DocumentClient?
I am new to DynamoDB. 我是DynamoDB的新手。 I have a DynamoDB table called 'kids-profiles' that lists child profiles for a user (primary partition key 'userId', primary sort key 'childId'). 我有一个名为'kids-profiles'的DynamoDB表,它列出了用户的子配置文件(主分区键'userId',主排序键'childId')。 I have a second table called 'kids-tasks' that lists tasks for a child (primary partition key 'childId', primary sort key 'taskId'). 我有一个名为'kids-tasks'的第二个表,它列出了一个孩子的任务(主分区键'childId',主分类键'taskId')。 I would like to atomically add an item to the 'kids-tasks' table only if the 'childId' exists in the 'kids-profiles' table. 我希望只有在'kids-profiles'表中存在'childId'时,才能将项目原子地添加到'kids-tasks'表中。
I am trying to use the transactWrite method of the AWS.DynamoDB.DocumentClient class ( https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html ) to achieve this, but I can't get it to work. 我正在尝试使用AWS.DynamoDB.DocumentClient类( https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html )的transactWrite方法来实现此目的,但我不能让它工作。 First, when I try to add a ConditionCheck to the TransactionItems, it says "TransactItems can only contain one of Check, Put, Update or Delete". 首先,当我尝试将ConditionCheck添加到TransactionItems时,它说“TransactItems只能包含Check,Put,Update或Delete之一”。 So I have changed "ConditionCheck" to "Check" instead, assuming that is correct even though it is not mentioned in the documentation. 所以我已经将“ConditionCheck”改为“Check”,假设即使文档中没有提到它也是正确的。 Second, when I do get it to execute, it adds the task to the 'kids-tasks' table regardless of whether or not the 'childId' exists in the 'kids-profiles' table. 其次,当我确实执行它时,它会将任务添加到'kids-tasks'表中,而不管'children-profiles'表中是否存在'childId'。
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");
}
Divide objects into individual Operations. 将对象划分为单独的操作。
const params = {
TransactItems: [
{
ConditionCheck: {
...
},
+ }, // <------ !!!!!
+ {
Put: {
...
}
]
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.