Martin Stryffeler
Martin Stryffeler

Reputation: 81

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);
});

Upvotes: 8

Views: 10657

Answers (2)

joshuakcockrell
joshuakcockrell

Reputation: 6113

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.

Upvotes: 10

notionquest
notionquest

Reputation: 39156

Here is the working code. You don't need ADD here. Just use "set friends = :friendId" as friends attribute is not already present in the table (i.e. before the update you have only id, name and password in the table). The friend attribute is being added newly 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"
};

Upvotes: 0

Related Questions