删除 dynamodb 中的列表元素,索引是存储在变量中的值

Yas*_*aka 6 javascript list amazon-dynamodb aws-lambda

我正在尝试从列表中删除一个项目。当我硬编码项目的索引(即 REMOVE relatedUsers[0])但我在变量中找到索引时,更新表达式起作用。因此,我尝试使用 ExpressionAttributeValues 替换更新表达式中的变量,但收到错误“无效的 UpdateExpression:语法错误;标记:\":userIndex\",附近:\"[:userIndex]\"'

这是我的代码

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);
        }
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用 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',
    };
Run Code Online (Sandbox Code Playgroud)

但它没有更新数据库中的任何内容。你能帮我解决这个问题吗?

F_S*_*O_K 5

实际上,您只是构建一个查询字符串,因此请尝试使用文字:

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);
        }
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)