如何从 DynamoDB 中的 StringSet 中删除一个项目?

How to remove an item from a StringSet in DynamoDB?

我在 DynamoDB 中有这个 table:

{
  "lectures": {
    "L": [
      {
        "M": {
          "lecture_id": {
            "S": "CC0"
          },
          "students": {
            "SS": [
              "",
              "test"
            ]
          }
        }
      }
   ]
}

我想从 StringSet students 中删除 "test"

查看the docs,我试过这段代码:

function removeLecture(event){
    const students = 'lectures[' + Number.parseInt(event.lecture_id) + '].students';
    console.log('test: ' + students);
    const params = {
        TableName: 'TableName',
        Key: {
            'Key': key
        },
        UpdateExpression: `DELETE ${students} :student`,
        ExpressionAttributeValues: {
            ':student' : {
                'SS': event.student
            }
        },
        ReturnValues : 'UPDATED_NEW'
    }
    
    return ddb.update(params).promise();
}

无论如何,我收到一个 ValidationException:

START RequestId: 3857a2c2-23a8-4c0c-b080-516669c6e615 Version: $LATEST
2021-08-18T10:21:39.078Z    3857a2c2-23a8-4c0c-b080-516669c6e615    INFO    test: lectures[0].students
2021-08-18T10:21:39.831Z    3857a2c2-23a8-4c0c-b080-516669c6e615    INFO    ValidationException: Invalid UpdateExpression: Incorrect operand type for operator or function; operator: DELETE, operand type: MAP, typeSet: ALLOWED_FOR_DELETE_OPERAND

我也尝试过 ExpressionAttributeValues: {':student' : event.student},但我仍然收到与 STRING 相同的错误,而不是 MAP

如何从 StringSet 中删除字符串?

经过长时间的尝试,我发现了 AWS.DynamoDB.DocumentClient class 的功能 createSet()。我尝试使用它,并且有效。所以答案是:如果你想从一个 StringSet 中删除一个 String,你必须创建另一个 StringSet 并将后者从原来的 .

中删除

代码如下:

function removeLecture(event){
    const students = 'lectures[' + Number.parseInt(event.lecture_id) + '].students';
    console.log('test: ' + students);
    const params = {
        TableName: 'TableName',
        Key: {
            'Key': key
        },
        UpdateExpression: `DELETE ${students} :student`,
        ExpressionAttributeValues: {
            ':student' : ddb.createSet(event.student)
        },
        ReturnValues : 'UPDATED_NEW'
    }
    
    return ddb.update(params).promise();
}