Forgive me if this has already been asked and I have missed it but this has been bugging me all weekend and I do not know what I am doing wrong. I am trying to make a PUT request using the $resource service in angular.js with the ngResource module. I am fairly new to angular so if I am making rookie mistakes again apologies... on the learning curve.
I have followed the guidelines at the bottom of the official page at the angular docs here:
https://docs.angularjs.org/api/ngResource/service/$resource
I am making a GET request to my backend and pulling in a 'group' object, one of the properties of which is called 'teams', which is an empty array.
I then have functionality for a user to create a team via a form and then save it to mongodb. I automatically want the team to get added to the user group they are a part of, so I want the group object to add the team to the teams array and then perform the PUT. I have a Groups service which I am injecting as a dependency to the controller. I am doing the following:
app.controller('teamsController', ['$scope', '$http', '$routeParams', '$location', 'Teams', 'Groups', function ($scope, $http, $routeParams, $location, Teams, Groups) {
$scope.createTeam = function () {
var team = new Teams({.... }); //create the new team with all the data required
var groupId = this.team.group; //get the id to pull the correct group id from mongodb
//use Groups service to pull in the group to update, save it as a variable group
Groups.get({groupId: groupId}).$promise.then(function(group) {
var group = group;
group.teams.push(team); //push the team to the teams array in the group
console.log(group); //This logs exactly what I am hoping for with the new team in the teams array on the group object
//save the new team to the database, update the group by adding the new team to the teams array then go to the new team page
team.$save(function (response) {
Groups.update({id: groupId}, group);
$location.path("teams/" + response._id);
});
});
};
}]);
My team gets created how it should, and I am getting a successful 200 back from the server on the PUT request, but for some reason the team is not being added to the teams array on the group object. If I am missing something blatant... apologies in advance. Any help would be greatly appreciated. Here is my Groups service:
app.factory('Groups', ['$resource', function('$resource') {
return $resource(
'api/v1/groups/:groupId',
{
groupId: '@_id'
},
{
update: {method: 'PUT'}
}
);