I am trying to enter an object into teams
field but it’s overwriting existing one. What am i doing wrong here?
table
{
{
id: '1', // PK
name: 'basketball',
teams: {}
},
{
id: '2', // PK
name: 'soccer',
teams: {}
}
}
current code
let team = {
TableName: table,
Key: {id: event.gameId},
UpdateExpression: `SET teams = :n`,
ExpressionAttributeValues:{
":n":{[event.teamId]: {teamId: event.teamId, teamName: event.teamName}},
},
ReturnValues:"UPDATED_NEW"
};
try {
await dbClient.update(teamBody).promise();
return { statusCode: 200, message: "Success"};
} catch (err){
return {error: err};
}
expected result
{
id: '1', // PK
name: 'basketball',
teams: {
'1': {teamId:'1', teamName: 'Blue'},
'2': {teamId:'2', teamName: 'Red'},
}
}
2
Answers
You are navigating to the teams attribute index of your item before performing the update. You need to go one level deeper in your SET to ‘SET teams.#teamId = :n’.
Update expressions is a great page to review for your use case. Review the sections on adding lists, maps, and there’s a section about working with nested attributes that you might find useful.