DynamoDB / marshal 函数抱怨未定义的值

Ada*_*dam 14 javascript amazon-dynamodb typescript

当我尝试使用 将 JavaScript 对象持久保存到 DynamoDB 时PutCommand,我看到以下错误消息:

Error: Pass options.removeUndefinedValues=true to remove undefined values from map/array/set.
Run Code Online (Sandbox Code Playgroud)

当我使用时会发生这种情况DynamoDBDocumentClient

当我使用then 时,我必须首先使用fromDynamoDBClient封送对象。在这种情况下,当我尝试封送对象时会显示错误。marshall(..)@aws-sdk/util-dynamodb

当我将对象打印到控制台时,我没有看到任何未定义的值。但是,由于嵌套级别太多,我看不到完整的对象:

{ id: 123, child: { anotherChild: { nested: [Object] } } }
Run Code Online (Sandbox Code Playgroud)

所以我用它JSON.stringify(..)来显示整个对象:

{
    "id": 123,
    "child": {
        "anotherChild": {
            "nested": {
                "name": "Jane"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我显然没有任何未定义的属性,那么为什么我会看到错误消息?

Ada*_*dam 13

如果函数marshal(..)遇到未定义的属性,则会抛出此错误。

marshall({
    name: "John",
    age: undefined,
})
Run Code Online (Sandbox Code Playgroud)

我的对象确实有一个未定义的值,但事实证明这JSON.stringify(..)删除具有未定义值的属性

我必须添加一个“替换函数”来JSON.stringify(..)查看(并修复)未定义的值。

import {marshall} from "@aws-sdk/util-dynamodb";

const myObject = {
    id: 123,
    child: {
        anotherChild: {
            nested: {
                name: "Jane",
                age: undefined,
            },
        },
    },
};

// Doesn't show the undefined value (too many levels of nesting)
console.log(myObject);

// Doesn't show the undefined value (silently removes undefined attributes)
console.log(JSON.stringify(myObject));

// DOES show the undefined value
console.log(JSON.stringify(myObject, (k, v) => v === undefined ? "!!! WARNING UNDEFINED" : v));

// The marshall function throws an error due to the presence of an undefined attribute
marshall(myObject);
Run Code Online (Sandbox Code Playgroud)


小智 9

您应该使用该对象来指定和 的translateConfig行为,如下所述:marshallunmarshall

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_lib_dynamodb.html#configuration

您可以使用以下设置来处理undefined值。