Question

I'm trying to get a handle on using $resource in angularjs and I keep referencing this answer AngularJS $resource RESTful example for good examples. Fetching a record and creating a record work fine, but now i'm trying to add a "section" to an existing mongo record but can't figure it out.

documents collection

{
  _id: 'theid', 
  name: 'My name", 
  sections: [
    {
      title: 'First title'
    },
    {
      title: 'Second title'
    }
  ]
}

angular controller snippet

var document = documentService.get({_id: 'theid'});
// TRYING TO ADD $scope.section TO THE SECTIONS ARRAY IN THE VARIABLE document.
//document.sections.push($scope.section); <-- This does NOT work
//document.new_section($scope.section); <-- could do this and then parse it out and insert it in my backend code, but this solution seems hacky and terrible to me.
document.$save(function(section) {
     //$scope.document.push(section);
});

documentService

return $resource(SETTINGS.base + '/documents/:id', { id: '@id' },
      {
        update: { method: 'PUT' }
      });

From the link i posted above, If I was just updating the name field, I could just do something like this:

var document = documentService.get({_id: 'theid'});
document.name = "My new name";    
document.$save(function(section) {
    //$scope.document.push(section);
});

I'm just trying to add an object to a nested array of objects.

Was it helpful?

Solution

Try this:

documentService.get({_id: 'theid'}, function(document) {
    document.sections.push($scope.section);
    document.$save();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top