Reputation: 1246
I have a simple JSON array that I am trying set a map key on using a variable. The array uses the map functionality of DynamoDB and the first map called 'hours' contains a nested Map that I want to have a key of 15. However becuase I want that key to change depending on the hour of the day, I passed a variable into the JSON array nested map key that would reflect that.
For the following I just hard coded it to 15 to simplify the problem.
The issue is that DynamoDB does in fact run the putItem with this in there it changes the variable hour to just a string "hour" and ignores the value of the set variable during the operation. Any ideas on how to pass the variable value to the key name?
var hour = "15";
"hours" : {"M" : {
hour : {"M" : { //The hour variable is used as a key
"action1" : {"N" : "1"},
"action2" : {"N" : "1"}
}
}
}
}
Upvotes: 1
Views: 2211
Reputation: 480
Use ExpressionAttributeNames:
and ExpressionAttributeValues:
in your params
. The following (using documentClient to convert javascript types automatically) should hopefully point you in the right direction but you will have to decide if you're adding new #hr
nestedfields, deleting old ones, etc and, also, this only works if the #hrs
map exists to begin with in the item--even if as an empty map. Finally, this will overwrite existing #hr
nestedfields if they already exists or create new ones if they don't. Again, not sure of your absolute need here.
var hour = 15; //or whatever number you need
var dynamoDBdc = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: <yourtablename>,
Key: <yourkey>,
UpdateExpression: "SET #hrs.#hr = :value",
ExpressionAttributeNames: {"#hrs": "hours", "#hr": hour.toString()},
ExpressionAttributeValues: {":value": {"action1": 1, "action2": 2}},
ReturnValues: "ALL_NEW" //or whatever you want here
};
dynamoDBdc.update(params, function(err, data) {
if(err) {
//handle it
}
else {
//your subsequent code
}
}
More info can be found here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html#ExpressionAttributeNames
and here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html
I hope this helps.
Upvotes: 3