【问题标题】:How to add a new object to an array nested inside an object?如何将新对象添加到嵌套在对象内的数组中?
【发布时间】:2014-04-24 20:35:07
【问题描述】:

我正在尝试在 angularjs 中使用 $resource,并且我一直在参考这个答案 AngularJS $resource RESTful example 以获得很好的示例。获取记录并创建记录工作正常,但现在我正在尝试将“部分”添加到现有的 mongo 记录但无法弄清楚。

文档集合

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

角度控制器sn-p

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);
});

文档服务

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);
});

我只是想将一个对象添加到嵌套的对象数组中。

【问题讨论】:

  • $scope.document.sections.push(section) - 顺便说一下,get 调用是异步的,您需要回调!
  • 我不是试图推送到一个范围变量,而是我试图在document 上设置它,以便它在 mongo 中得到更新。基本上根据我的理解,我的文档变量是从 mongo 获取记录,然后我正在更新一些值(或者在这种情况下我正在添加到数组中),然后我将其保存回 mongo。至少这是我想要达到的目标。
  • 你定义了后端$save函数吗?
  • $save 是一个角度 $resource 方法。
  • 我知道...它在您的服务器上调用了一个方法。

标签: javascript angularjs mongodb mean-stack


【解决方案1】:

试试这个:

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

【讨论】:

  • 这似乎让我解决了这个问题,但它正在做一个POSTlocalhost:3000/documents/1。我原以为它会执行PUT 以便更新记录。这是一个奇怪的角度吗?
  • 我相信这是 resource 接线 - 虽然我一直认为 put 用于创建全新的对象,POST 用于更新......嗯
  • 不,你搞错了。
  • 啊,该死的!好吧,你总是可以保存一个全新的对象,所以我猜POST 是全部
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2015-09-11
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多