Update an Array Column

Update an array column.

To help with storing array data, there are three operations that can be used to automatically change an array field:

  • Add – appends the given array of objects to the end of an array field.
  • AddUnique – adds only the given objects that aren’t already contained in an array field. The position of the insert is not guaranteed.
  • Remove – removes all instances of each given object from an array field.

Each method takes an array of objects to add or remove in the objects key. Use a PUT command to add an array of objects. Remember to paste the object ID in the end of the URL.

https://api.appery.io/rest/1/db/collections/<collectionName>/<objectId>

The result is JSON containing the object update time.

Example

curl -X PUT
  -H "X-Appery-Database-Id: 544a5cdfe4b03d005b6233b9"
  -H "Content-Type: application/json"
  -d '{"marks":{"__op":"AddUnique","objects":[5, 2]}}'
  https://api.appery.io/rest/1/db/collections/students/544fc7f1e4b0c9bce1295c78
{
    "_updatedAt":"2015-06-15 15:05:53.061"
}

__op defines a kind of operation. It can be Add, AddUnique, and Remove, as in the example above.

When working with arrays, make sure you:

  1. Clean the localStorage variable value after you store the array to the database. Otherwise, you can get incorrect data, and errors will appear.
  2. Check the type of the array and database elements – they should be the same.

For example, when you store an array of objects to the database and you have this in a column:

["{name=xxxxxx, email=xxxxxx@xxxxxx}","{name=xxxxxx, email=xxxxxx@xxxxxx}"]

This means you stored an array of strings, not array of objects. You will get a TypeError message, because you have no objects in the array.

In this case, you should convert the strings to an array of objects. The following JavaScript code example can help:

function strRepresentationToObject(str) {
    str = str.slice(1, -1);
    var i, len, obj={}, tmp, arr = str.split(', ');
    for (i = 0, len = arr.length; i < len; i++) {
        tmp = arr[i].split('=');
        obj[tmp[0]] = tmp[1];
    }
    return obj;
}
if (value == "") {
return "[]";
}
var i, len, newValue = [];
for (var i = 0, len = value.length; i < len; i++) {
  newValue.push(strRepresentationToObject(value[i]));
}
return JSON.stringify(newValue);