DynamoDB update with composite primary key with node sdk

Viewed 1466

I'm looking to use the update function part of the document client in the dynamoDB javascript SDK. My dynamoDB table has a primary partition key of "PK" (String) and a primary sort key "SK" (String). My understanding is this means my items need to be identified with their composite primary key which is some combination of "PK" and "SK"

I am using a single table design so an example item would look like

PK "CONTEST#2021"

SK: "POST#5673"

author: "USER#2759"

text: "Lorem ipsum"

commentNumber: 9

The logic of my code looks like this

const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.addComment = async (event, context, callback) => {

const params = {
    TableName: 'App', 
    Key: {
        "PK": event.PK,
        "SK": event.SK
    },       
    UpdateExpression: 'set commentNumber = :number',
    ExpressionAttributeValues: {
        ':number': event.updatedCommentCount
    }
}

try {
    var res = await dynamo.update(params).promise()
    // handleSuccess(res)
} catch(err) {
    // handleFail(err)
}

return 'success'

};

When I try the code above, i get an error saying the provided key element does not match the schema

I know there's something wrong with the Key key in my params, but the documentation isn't helping. It suggests it's possible to update with a composite key and seems to suggest that the value for Key can be an object with two keys, but this isn't working. How can I update my params to use the update function?

1 Answers

I believe you have to use # in front of attribute names like so: ...UpdateExpression: 'set #commentNumber = :number',...

Related