【问题标题】:How to pass null value from a json to dynamodb如何将空值从 json 传递到 dynamodb
【发布时间】:2019-08-14 04:02:53
【问题描述】:

我想将值一个一个地传递给 lambda 函数并将该数据存储到 dynamodb 中,但是当我保存第一个值时,该值表示该值不能为空。

我尝试了以下方法:

  1. 添加 convertEmptyValues: true

    var doClient = new AWS.DynamoDB.DocumentClient({convertEmptyValues: true});

  2. 添加了三元运算符来传递值,例如,

    "age": event.age == '' ? null : event.age,

    "age": event.age === null ? null : event.age

但我遇到了同样的错误:Error: TypeError: Cannot read property 'age' of null at exports.handler 并且该值没有存储在数据库中。

var AWS = require("aws-sdk");

AWS.config.update({
    region: "us-east-1",
});

var doClient = new AWS.DynamoDB.DocumentClient({
  convertEmptyValues: true
});

exports.handler = function(event,callback) {
    var flows =  {
        "activities": [
          {
            "gender": event.flows.activities[0].gender,
          },
          {
            "age": event.flows.activities[1].age == '' ? null : event.flows.activities[1].age,
          },
          {
            "zipCode": event.flows.activities[2].zipCode == '' ? null : event.flows.activities[2].zipCode,
          },
          {
           //More Code
          },
        ]
      };
}

【问题讨论】:

  • 从您得到的错误看来,event.flows.activities[1]null。您应该确保该函数获得预期值。
  • 这个函数会在我传值后获取值,因为到那时它应该作为空值传递。

标签: node.js aws-lambda amazon-dynamodb


【解决方案1】:

您正在检查空值的错误内容。您使用的三元表达式没有任何作用——拥有age: x.age === null ? null : x.age 与拥有age: x.age 完全相同。

但是,在您的情况下,问题是在表达式 x.age 中,x 的值是 null,这意味着您是试图访问nullage 属性,这会导致错误。您的三元表达式应该检查x 本身是否为null

你的代码应该是这样的:

const AWS = require("aws-sdk");
AWS.config.update({
    region: "us-east-1",
});
const doClient = new AWS.DynamoDB.DocumentClient({
    convertEmptyValues: true
});

exports.handler = function(event,callback) {
    var flows =  {
        "activities": [
        {
            "gender": event.flows.activities[0].gender,
        },
        {
            "age": event.flows.activities[1] === null ? null : event.flows.activities[1].age,
        },
        {
            "zipCode": event.flows.activities[2] === null ? null : event.flows.activities[2].zipCode,
        },
        {
        //More Code
        },   
   ]
};
}

【讨论】:

  • 如果我想在值为空的情况下跳过这一步,我可以这样做吗? @Kalev
猜你喜欢
  • 2015-09-18
  • 1970-01-01
  • 2021-05-15
  • 2014-08-11
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 2017-09-29
相关资源
最近更新 更多