AWS DynamoDB Attempting to add to set - invalid operand

I am creating an API using Nodejs and DynamoDB as the back end. I am trying to update an item to add to the friends set. When I update a user, I get the error message "Invalid UpdateExpression: invalid operand type for operator or function: operator: ADD, operand type: MAP". I understand that when added to a set that does not exist, the set will be created. If it already exists, the new value should be added to the set. I don’t understand why the set that I am trying to add to the ADD reads like a map.

How users are created:

var params = { TableName: "users", Item:{ "id": Number(id), "name": name, "password": password } }; documentClient.put(params, function(err, data) { if(err) res.json(500, err); else res.json(200, data); }); 

How to add friends:

 var params = { TableName: "users", Key: { "id": id }, UpdateExpression: "ADD friends :friendId", ExpressionAttributeValues: { ":friendId": { "NS": [friendId] } }, ReturnValues: "UPDATED_NEW" }; documentClient.update(params, function(err, data) { if(err) res.json(500, err); else res.json(200, data); }); 
+2
source share
2 answers

There is an answer in this question

fooobar.com/questions/1254782 / ...

Here is the appropriate code formatted according to your question

 let AWS = require('aws-sdk'); let docClient = new AWS.DynamoDB.DocumentClient(); ... var params = { TableName : 'users', Key: {'id': id}, UpdateExpression : 'ADD #friends :friendId', ExpressionAttributeNames : { '#friends' : 'friends' }, ExpressionAttributeValues : { ':friendId' : docClient.createSet([friendId]) }, ReturnValues: 'UPDATED_NEW' }; docClient.update(params, callback); 

If the set does not exist, then this code will create it for you. You can also run this code with a different set to update installed items. Super comfortable.

+3
source

Here is the working code. You do not need to ADD here. Just use "set friends =: friendId", because the friends attribute is not yet in the table (for example, before updating the table only has an identifier, name and password). The friend attribute is added recently as part of the update.

 var docClient = new AWS.DynamoDB.DocumentClient(); var table = "users"; var userid = 1; var friendId = [123]; var params = { TableName : table, Key: { "id" : userid }, "UpdateExpression": "set friends = :friendId", "ExpressionAttributeValues": { ":friendId": {"NS": friendId} }, "ReturnValues" : "UPDATED_NEW" }; 
0
source

All Articles