【发布时间】: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