Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - DynamoDB update with composite primary key with node sdk

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?

question from:https://stackoverflow.com/questions/65913282/dynamodb-update-with-composite-primary-key-with-node-sdk

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...