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

使用Adonis(Node.js)调用DynamoDB时遇TypeError错误求助

解决DynamoDB DocumentClient的TypeError: translator.translateInput is not a function错误

这个错误其实是因为你混用了DynamoDB两种不同客户端的使用方式,我来帮你拆解问题并修复:

问题根源

  1. 参数格式不匹配:你写的dynamoDB_params是原生DynamoDB客户端需要的格式(带S、N、M这些类型标识),但你却把它传给了DocumentClient——这个高层封装的客户端不需要手动指定类型,它会自动帮你推断。格式不兼容导致内部类型转换逻辑出错,抛出了translator.translateInput is not a function。
  2. DocumentClient实例化错误:你用AWS.DynamoDB.DocumentClient()而不是new AWS.DynamoDB.DocumentClient(),缺少new关键字,导致没有正确创建客户端实例。
  3. 异步操作未正确处理:put方法是异步的,你直接调用它不会返回操作结果,而是返回一个请求对象,需要用.promise()配合await来获取结果。

修复后的完整代码

const AWS = require('aws-sdk');
// 先配置AWS区域(如果没通过环境变量配置的话)
AWS.config.update({ region: 'your-region' }); // 替换成你的实际区域,比如us-east-1
// 创建DocumentClient实例
const docClient = new AWS.DynamoDB.DocumentClient();

async testing({ params, response }) {
  var table_name = 'testing8';
  var year = "2015";
  var title = "The Big New Movie";

  // 使用DocumentClient的参数格式,不需要手动指定类型
  var dynamoDB_params = {
    TableName: table_name,
    Item: {
      "year": year,
      "title": title,
      "info": {
        "plot": "Nothing happens at all.",
        "rating": 0 // 直接传数字,DocumentClient自动转为N类型
      }
    }
  };

  try {
    // 异步调用put方法,用promise+await获取结果
    const data = await docClient.put(dynamoDB_params).promise();
    response.json({ success: true, message: '数据插入成功', data: data });
  } catch (err) {
    // 捕获错误并返回
    response.status(500).json({ success: false, error: err.message });
  }
}

额外说明

  • 如果以后需要用原生DynamoDB客户端(比如有特殊类型处理需求),要这样创建:const dynamodb = new AWS.DynamoDB(),然后调用它的putItem方法,此时你的原始参数格式是正确的。
  • 推荐优先使用DocumentClient,它简化了数据类型的处理,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:28:12