如何使用Node.js删除DynamoDB中的嵌套项?

huangapple go评论70阅读模式
英文:

How to delete nested item in DynamoDB using node?

问题

我正在尝试从 teams 对象中删除一个项目。

我的游戏表格如下所示

{
   "gameId": "1", //PK
   "teams": {
     "1": {"id": "1", "teamName": "Blue"},
     "2": {"id": "2", "teamName": "Red"}
   }
}

我的代码如下

let team = {
   TableName: table,
   Key: {"id": event.pathParameters.gameId},
   ConditionExpression: "#t.#n = :val",
   ExpressionAttributeNames: {
        "#t": "teams",
        "#n": event.pathParameters.teamId
   },
   ExpressionAttributeValues: {
         ":val" : event.pathParameters.teamId
   }
};
                        
try {
   
  await dbClient.delete(team).promise();

} catch (err){
                            

  return {error: err};

}

但我收到以下错误

条件请求失败

我做错了什么???

英文:

I am trying to delete an item from teams object.

My game table looks like this


{
   gameId: "1", //PK
   teams: {
     1: {id: "1", teamName: "Blue"},
     2: {id: "2", teamName: "Red"}
   }
}

My code looks like this

let team = {
   TableName: table,
   Key: {id: event.pathParameters.gameId},
   ConditionExpression: "#t.#n = :val",
   ExpressionAttributeNames: {
        "#t":"teams",
        "#n": event.pathParameters.teamId
   },
   ExpressionAttributeValues: {
         ":val" : event.pathParameters.teamId,
         "#n": event.pathParameters.teamId
   }
};
                        
try {
   
  await dbClient.delete(team).promise();

} catch (err){
                            
  return {error: err};

}

But i am getting following error

The conditional request failed

What am i doing wrong???

答案1

得分: 2

如果我理解正确,您正在尝试删除项目中的一个属性,而不是整个项目,所以您的基本概念在这里是错误的。

let team = {
   TableName: table,
   Key: {id: event.pathParameters.gameId},
   UpdateExpression: "remove #t.#n",
   ExpressionAttributeNames: {
        "#t": "teams",
        "#n": event.pathParameters.teamId
   }
};
                        
try {
   
  await dbClient.update(team).promise();

} catch (err){
                            
  return {error: err};

}
英文:

If I understand correctly you're trying to delete an attribute within an item, and not a whole item, so your fundamentals are wrong here

let team = {
   TableName: table,
   Key: {id: event.pathParameters.gameId},
   UpdateExpression: "remove #t.#n",
   ExpressionAttributeNames: {
        "#t":"teams",
        "#n": event.pathParameters.teamId
   }
};
                        
try {
   
  await dbClient.update(team).promise();

} catch (err){
                            
  return {error: err};

}

huangapple
  • 本文由 发表于 2023年7月12日 22:01:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定