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

3 posts, 0 answers
  1. eliandrolima
    eliandrolima avatar
    2 posts
    Member since:
    Aug 2013

    Posted 06 Oct Link to this post

    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. Martin
    Admin
    Martin avatar
    67 posts

    Posted 10 Oct Link to this post

    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.
     
  3. eliandrolima
    eliandrolima avatar
    2 posts
    Member since:
    Aug 2013

    Posted 03 Nov in reply to Martin Link to this post

    It helped a lot. It was exactly what I was wondering.

    Thanks man!
Back to Top