Currently, I am delving into the world of using $resource
in angularjs and finding great examples in this answer AngularJS $resource RESTful example. Fetching and creating records is working fine, but now my challenge lies in adding a "section" to an existing mongo record and struggling to figure it out.
Within the documents collection:
{
_id: 'theid',
name: 'My name",
sections: [
{
title: 'First title'
},
{
title: 'Second title'
}
]
}
The snippet from the angular controller:
var document = documentService.get({_id: 'theid'});
// ATTEMPTING 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 function:
return $resource(SETTINGS.base + '/documents/:id', { id: '@id' },
{
update: { method: 'PUT' }
});
Referring back to the provided link, for updating the name
field, something like the following works:
var document = documentService.get({_id: 'theid'});
document.name = "My new name";
document.$save(function(section) {
//$scope.document.push(section);
});
My focus is on inserting an object into a nested array of objects.