4
votes

I'm trying to remove an item from the list. The update expression works when I hard code the index of the item (i.e. REMOVE relatedUsers[0]) but I have the index found in a variable. So I tried using ExpressionAttributeValues to replace the variable in the update expression but I'm getting the error 'Invalid UpdateExpression: Syntax error; token: \":userIndex\", near: \"[:userIndex]\"'

Here is my code

function updateUser(data) {
    console.log('---------updateUser---------');
    console.log(data);
    const params = {
      TableName: process.env.USER_TABLE,
      Key: {
        id: data.id,
      },
      ExpressionAttributeValues: {
        ':updatedAt': timestamp,
        ':notificationCount':1,
        ':userIndex':data.index,
      },
      UpdateExpression: 'ADD notificationCount :notificationCount REMOVE relatedUsers[:userIndex] SET updatedAt= :updatedAt ',
      ReturnValues: 'ALL_NEW',
    };

    return new Promise((resolve, reject)=>{
      dynamodb.update(params, (error,data) => {
        // handle potential errors
        if (error) {
          reject(error);
        }
        else {
          console.log("update consultant response");
          console.log(data);
          resolve(data);
        }
      });
    });
  }

I also tried with ExpressionAttributeNames

function updateUser(data) {
    console.log('---------updateUser---------');
    console.log(data);
    let relatedUser = 'relatedUsers[' + data.index + ']'
    const params = {
      TableName: process.env.USER_TABLE,
      Key: {
        id: data.id,
      },
      ExpressionAttributeNames: {
          '#user':relatedUser
      },
      ExpressionAttributeValues: {
        ':updatedAt': timestamp,
        ':notificationCount':1,
      },
      UpdateExpression: 'ADD notificationCount :notificationCount REMOVE #user  SET updatedAt= :updatedAt ',
      ReturnValues: 'ALL_NEW',
    };

But it didn't update anything in db. Can you help me resolve this situation?

1

1 Answers

3
votes

Effectively you are just building a query string, so try using a literal instead:

function updateUser(data) {
    console.log('---------updateUser---------');
    console.log(data);
    const params = {
      TableName: process.env.USER_TABLE,
      Key: {
        id: data.id,
      },
      ExpressionAttributeValues: {
        ':updatedAt': timestamp,
        ':notificationCount':1
      },
      UpdateExpression: "ADD notificationCount :notificationCount REMOVE relatedUsers[" + data.index + "] SET updatedAt= :updatedAt",
      ReturnValues: 'ALL_NEW',
    };

    return new Promise((resolve, reject)=>{
      dynamodb.update(params, (error,data) => {
        // handle potential errors
        if (error) {
          reject(error);
        }
        else {
          console.log("update consultant response");
          console.log(data);
          resolve(data);
        }
      });
    });
  }