Append a new object to a JSON Array in DynamoDB using NodeJS
Use list_append()
and if_not_exists()
together in an UpdateExpression to append to a potentially non-existent list column:
var AWS = require('aws-sdk')
var DB = new AWS.DynamoDB.DocumentClient()
function appendMarkedLocation (personId, location) {
return DB.update({
TableName: 'people',
Key: { id: personId },
ReturnValues: 'ALL_NEW',
UpdateExpression: 'set #markedLocations = list_append(if_not_exists(#markedLocations, :empty_list), :location)',
ExpressionAttributeNames: {
'#markedLocations': 'markedLocations'
},
ExpressionAttributeValues: {
':location': [location],
':empty_list': []
}
}).promise()
}
appendMarkedLocation('somePeronId', {
latitude: '22.11',
longitude: '22.55',
name: 'Ocean',
description: 'Ocean',
placeid: '32423423',
image: 'url/icean.png'
}).then(console.log)