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

Lambda更新DynamoDB balance.amount时“Unrecognized operation”错误排查

问题描述

我编写了用于更新DynamoDB中balance.amount属性的Lambda函数,代码如下:

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'});

exports.handler = async (event) => {
    const phone=event.phoneNumber;
     const amount=event.amountChange;
    const updateParams = {
    TableName: "mytable",
    Key: {
        phoneNumber: 
            phone
        
    },
    UpdateExpression: "SET #a = #a + :incre",
     ExpressionAttributeNames: {
    '#a': 'balance.amount',
  },
    ExpressionAttributeValues: {
        ":incre": 
            amount
        
    },
};
  await dynamodb.updateItem(updateParams).promise();

  return {
    statusCode: 200,
    body: JSON.stringify('Balance updated successfully')
  };
};

测试事件为:

{
  "phoneNumber": "+XXXXXXXXXX",
  "amountChange": 100
}

测试时出现如下错误:

{
  "errorType": "Error",
  "errorMessage": "Unrecognized operation \"undefined\"",
  "trace": [
    "Error: Unrecognized operation \"undefined\"",
    "    at Runtime.exports.handler (/var/task/index.js:39:19)",
    "    at Runtime.handleOnceNonStreaming (/var/runtime/Runtime.js:74:25)"
  ]
}

其中phoneNumber是DynamoDB的主键,我希望更新balance.amount的值,请问代码中哪部分出现了错误?


错误修复方案

问题出在DynamoDB DocumentClient的方法调用上:你用了updateItem,但DocumentClient的正确更新方法是update——updateItem是底层AWS.DynamoDB原生客户端的方法,和你实例化的DocumentClient不兼容,这才导致了"Unrecognized operation"错误。

修正后的完整代码:

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'});

exports.handler = async (event) => {
    const phone = event.phoneNumber;
    const amount = event.amountChange;
    const updateParams = {
        TableName: "mytable",
        Key: {
            phoneNumber: phone
        },
        UpdateExpression: "SET #a = #a + :incre",
        ExpressionAttributeNames: {
            '#a': 'balance.amount',
        },
        ExpressionAttributeValues: {
            ":incre": amount
        },
    };
    // 关键修改:将updateItem替换为update
    await dynamodb.update(updateParams).promise();

    return {
        statusCode: 200,
        body: JSON.stringify('Balance updated successfully')
    };
};

额外注意事项:

  • 如果目标数据中balance对象本身不存在,需要调整UpdateExpression避免报错:
    UpdateExpression: "SET #a = if_not_exists(#a, :zero) + :incre",
    // 同时在ExpressionAttributeValues中添加
    ":zero": 0
    
  • 确保Lambda的执行角色配置了dynamodb:UpdateItem权限,否则会出现权限不足的新错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:23:35