Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS DynamoDB Attempting to ADD to a Set - Incorrect Operand

I am creating an API using Nodejs and DynamoDB as a back end. I am attempting to update an item to add to a set of "friends". When I update the user, I get the error, "Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: MAP". My understanding is that when adding 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 do not understand why the set I attempt to ADD is being read as 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 friends are added:

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);
});
like image 440
Martin Stryffeler Avatar asked Jun 02 '16 01:06

Martin Stryffeler


1 Answers

This question has an answer here

https://stackoverflow.com/a/38960676/4975772

Here's the relevant code formatted to fit 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 doesn't exist, then that code will create it for you. You can also run that code with a different set to update the set's elements. Super convenient.

like image 183
joshuakcockrell Avatar answered Oct 14 '22 00:10

joshuakcockrell