我在尝试更新任何文档子数组时使用angular-fullstack和Mongolabs,Mongolabs中存储的值只是数组中第一个元素的重复值。
Mongoose架构设置为
techspecs: [{label: String, value: String, _id: false}],
更新有效负载时显示正确并包含不同的值,例如
techspecs: [{label: "Dimensions", value: "1200x800mm"}, {label:"Capacity", value: "532 l"}]
然而,在Mongolabs中,值存储为
"techspecs": [
{
"label": "Dimensions",
"value": "1200x800mm"
},
{
"label": "Dimensions",
"value": "1200x800mm"
}
],
如果我有更多的值对,它只会存储第一个元素的多个副本。
使用$ resource通过工厂服务
完成更新angular.module('prototypeMeanApp')
.factory('productAPI', ['$resource', function($resource) {
return $resource('api/products/:id', {id: '@_id'}, {
'update': { method:'PUT'},
'create': { method:'POST'},
'query' : {method:'GET', isArray:true}
});
}
]);
在控制器中,它通过以下功能进行更新
$scope.updateProduct = function(form) {
$scope.submitted = true;
var pId = $scope.product._id;
if(form.$valid) {
productAPI.update({id: pId}, {
_id: pId,
categoryid: $scope.currentcat[0]._id,
brand: $scope.product.brand,
model: $scope.product.model,
heading: $scope.product.heading,
description: $scope.product.description,
price: $scope.product.price,
techspecs: $scope.product.techspecs,
lastmodified: Date.now()
}).$promise.then(function() {
console.log('Product updated');
}, function(err) {
err = err.data;
$scope.errors = {};
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
在视图中
<div class="form-group" data-ng-repeat="techspec in product.techspecs">
<label class="control-label hidden-xs col-sm-3">Tech Spec #{{$index+1}}</label>
<div class="col-sm-4 col-md-3">
<div class="controls">
<input type="text" data-ng-model="techspec.label" class="form-control" placeholder="Label" />
</div>
</div>
<div class="col-sm-4 col-md-3">
<div class="controls">
<input data-ng-model="techspec.value" type="text" class="form-control" placeholder="Value" />
</div>
</div>
</div>
答案 0 :(得分:3)
我最终用mean.io进行了一个简单的测试,以验证这是否可行,并且Mean.io成功地将文档子数组存储到Mongo中。在此之后,我比较了angular-fullstack和mean.io的源和实现方法,看看有什么不同。
最后证明是更新函数中使用的lodash方法。
angular-fullstack使用_.merge
而mean.io在更改angular-fullstack代码后使用_.extend
使用_.extend
将子数组正确存储到MongoDB中
对于任何使用angular-fullstack的人。编辑服务器端点控制器server / api / products / product.controller.js
然后找到更新函数并用_.extend替换_.merge,例如
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
Product.findById(req.params.id, function (err, product) {
if (err) { return handleError(res, err); }
if(!product) { return res.send(404); }
var updated = _.extend(product, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, product);
});
});
};