How can I put a new value into PutCommand Item if variable is not "undefined" in DynamoDB

160 Views Asked by At

As the title said, I want to put a variable into one of its Item only if the variable is not undefine.

I've tried this code.

const createNewAccount = new PutCommand({
    TableName: tableName,
    Item : {
        "PK" : email,
        "SK" : type + "#" + school,
        "GSI1SK" : classroom + "#" + name,
    }
});

if(type == "STD"){
    createNewAccount.Item["number"] = number
}

const createNewAccountResponse = await client.send(createNewAccount);

Raise the error "Cannot set properties of undefined (setting 'number')" at the line createNewAccount.Item["number"] = number Also, my number variable is an integer, and all variables will not be undefine in this case.

I'm not sure is there a way to exactly solve this problem. If it has, please let me know.

Thank you!

2

There are 2 best solutions below

4
On BEST ANSWER

Try this:

const createNewAccount = {
    TableName: tableName,
    Item : {
        "PK" : email,
        "SK" : type + "#" + school,
        "GSI1SK" : classroom + "#" + name,
    }
};

if(type == "STD"){
    createNewAccount.Item["number"] = number
}

const createNewAccountResponse = await client.send(new PutCommand(createNewAccount));

Here is a full example which I tested:

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, PutCommand } = require("@aws-sdk/lib-dynamodb");

const client = new DynamoDBClient({ region: "eu-west-1" });
const docClient = DynamoDBDocumentClient.from(client);

const go = async () => {
    let type = 'STD';
    let number = 3
    const createNewAccount = {
        TableName: 'Test',
        Item: {
            "PK": '23',
            "SK": 'type' + "#" + 'school',
            "GSI1SK": 'classroom' + "#" + 'name',

        }
    };

    if (type == "STD") {
        createNewAccount.Item["number"] = number
    }

    const createNewAccountResponse = await docClient.send(new PutCommand(createNewAccount));

    console.log(createNewAccountResponse)
}

go();

And the result:

{
  '$metadata': {
    httpStatusCode: 200,
    requestId: 'requestId',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  Attributes: undefined,
  ConsumedCapacity: undefined,
  ItemCollectionMetrics: undefined
}
6
On

PutCommand is a class which does not expose the properties of the object you use to construct it. It's supposed to be immutable.

Use this:

const createNewAccount = new PutCommand({
    TableName: tableName,
    Item : {
        "PK" : email,
        "SK" : type + "#" + school,
        "GSI1SK" : classroom + "#" + name,
        ...(type == "STD" ? { number } : undefined)
    }
});

const createNewAccountResponse = await client.send(createNewAccount);