You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js操作DynamoDB追加List结构异常问题求助

解决DynamoDB待办列表新增任务结构不一致问题

问题背景

基于Node.js和DynamoDB开发待办列表新增模块时,出现新任务结构与原有任务不匹配的问题:

  • 数据库初始结构:
{
    "success": true,
    "toDoList": [
        {
            "L": [
                {
                    "S": "Task 1"
                },
                {
                    "BOOL": false
                }
            ]
        }
    ]
}
  • 发送POST请求:
{
    "petID": "the_pet_id",
    "newTask": "Task 2"
}
  • 新增后异常结构:
{
    "success": true,
    "toDoList": [
        {
            "L": [
                {
                    "S": "Task 1"
                },
                {
                    "BOOL": false
                }
            ]
        },
        {
            "M": {
                "BOOL": {
                    "BOOL": false
                },
                "S": {
                    "S": "Task 2"
                }
            }
        }
    ]
}
  • 期望结构:
{
    "success": true,
    "toDoList": [
        {
            "L": [
                {
                    "S": "Task 1"
                },
                {
                    "BOOL": false
                }
            ]
        },
        {
            "L": [
                {
                    "S": "Task 2"
                },
                {
                    "BOOL": false
                }
            ]
        }
    ]
}

错误原因

原有待办项是L类型(列表)的嵌套结构,而代码中构造的newTasks是普通对象,DynamoDB自动将其解析为M类型(映射),导致结构不匹配。

修正代码

将新任务的结构调整为与原有任务一致的L类型嵌套格式:

const { petID, newTask } = req.body

// 修正:按照原有结构,每个待办项是包含L属性的对象,L内是任务文本和完成状态的列表
const newTasks = [{ 
  L: [
    { S: newTask },
    { BOOL: false }
  ]
}]

const paramsUpdate = {
      TableName: 'PetBuddyToDoLists',
      Key: {
        PetID: petID,
      },
      UpdateExpression: 'SET ToDoList = list_append(ToDoList, :newTask)',
      ExpressionAttributeValues: {
        ':newTask':  newTasks,
      },
      ReturnValues: 'UPDATED_NEW',
    };

dynamoDB.update(paramsUpdate, (err, data) => {
      if (err) {
        console.error('Error updating list items:', err);
        res.status(500).json({ error: 'Error updating list items.' });
        return;
      }
      console.log('Item created successfully.', data);
      res.status(201).json({ message: 'Item created successfully.' });
    });

验证结果

修正后执行新增请求,查询数据库将得到与期望一致的结构,新任务和原有任务的格式完全匹配,前端可正常解析。

内容的提问来源于stack exchange,提问作者SOCRAMBLLE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:41:16