skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. let team = {
        TableName: table,
        Key: {id: event.gameId},
        UpdateExpression: `SET #t.#n = :n`,
        ExpressionAttributeValues:{
             ":n":{teamId: event.teamId, teamName: event.teamName},
        },
        ExpressionAttributeNames: {
            "#t":"teams",
            "#n": [event.teamId]
        }
        ReturnValues:"UPDATED_NEW"
    };
                        
    try {
         await dbClient.update(teamBody).promise();
         return { statusCode: 200, message: "Success"};
    } catch (err){
         return {error: err};
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search