This is a migrated thread and some comments may be shown as answers.

How can I append a object to a object using the Backend Services Javascript SDK?

2 Answers 38 Views
JavaScript SDK
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
eliandrolima
Top achievements
Rank 1
eliandrolima asked on 06 Oct 2016, 05:59 AM
Hi,

I have a Backend Services Data object that keep others objects. It's a array of objects. How can I append a object to this "array" using the Backend Services Javascript SDK?

For example:

The original object in the BS Data is...

contacts: [
  { 'firstname' : 'John', 'lastname' : 'Doe', 'age': 32 },
  { 'fisrtname' : 'Foo',  'lastname' : 'Bar', 'age': 48 }
]

So, I append the object { 'fisrtname' : 'Mary',  'lastname' : 'Ann', 'age': 27 }, and the result is:

contacts: [
  { 'firstname' : 'John', 'lastname' : 'Doe', 'age': 32 },
  { 'fisrtname' : 'Foo',  'lastname' : 'Bar', 'age': 48 },
  { 'fisrtname' : 'Mary',  'lastname' : 'Ann', 'age': 27 }
]


Thanks in advance!

2 Answers, 1 is accepted

Sort by
0
Martin
Telerik team
answered on 10 Oct 2016, 09:18 AM

Hi Eliandro,

To update an existing array field using the JavaScript SDK in your backend you use the native data queries operators ($push in your case - please see documentation on native operators). The code will look similar to the following:

var el = new Everlive('your-app-id');
.......


var data = el.data('type-name');
 
var attributes = {
    "$push": {
        "contacts": {
            "fisrtname": "Mary",
            "lastname": "Ann",
            "age": 27
        }
    }
};
 
var filter = {
    'Id': "item-id"
};
 
data.rawUpdate(attributes, filter, function(data) {
    console.log(JSON.stringify(data));
}, function(error) {
    console.log(JSON.stringify(error));
});

If you want to push multiple values to the array, you may use this:

var values = [{
    "fisrtname": "Mary",
    "lastname": "Ann",
    "age": 27
}, {
    "fisrtname": "John",
    "lastname": "Doe",
    "age": 32
}];
 
 
var attributes = {
    "$push": {
        "contacts": { "$each": values }
    }
};

Let me know if this has helped.

Regards,
Martin
Telerik by Progress
 
Everlive is now Telerik Backend Services, and is part of the Telerik Platform.
 
0
eliandrolima
Top achievements
Rank 1
answered on 03 Nov 2016, 02:30 PM
It helped a lot. It was exactly what I was wondering.

Thanks man!
Tags
JavaScript SDK
Asked by
eliandrolima
Top achievements
Rank 1
Answers by
Martin
Telerik team
eliandrolima
Top achievements
Rank 1
Share this question
or