如何将新对象添加到嵌套在对象中的数组?

时间:2014-04-24 20:35:07

标签: javascript angularjs mongodb mean-stack

我正试图在angularjs中使用$resource,并继续引用此答案AngularJS $resource RESTful example作为好例子。获取记录并创建记录工作正常,但现在我正在尝试将“部分”添加到现有的mongo记录中,但无法弄明白。

文件集

{
  _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' }
      });

从上面发布的链接中,如果我只是更新name字段,我可以这样做:

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

我只想尝试将对象添加到嵌套的对象数组中。

1 个答案:

答案 0 :(得分:1)

试试这个:

documentService.get({_id: 'theid'}, function(document) {
    document.sections.push($scope.section);
    document.$save();
});