[英]Ionic/NodeJS/MEAN - Put clears object data
我目前正在使用Node / Express和Ionic / Angular开发MEAN堆栈应用程序。 我有一个页面,用户可以在其中编辑/删除特定对象的内容。 删除功能有效,但是当我单击编辑并触发放置/更新功能时,它将清除ID号和“ __v”:0之外的数据,而不是更新对象。
我已经使用Postman检查了服务器端API,可以使用主体内容类型x-form-urlencoded对其进行更新。 我的直觉是在客户端正确获取数据。 任何帮助是极大的赞赏。
下面是我的离子/角度控制器代码:
.controller('UpdateCtrl', function($stateParams, $rootScope, $scope, HomeFac) {
id = $stateParams.id;
$scope.location = {};
HomeFac.getLocation(id).success(function(data) {
$scope.location = data;
});
$scope.edit = function() {
meet = $scope.location;
location = angular.fromJson(meet);
console.log(location);
HomeFac.updateLocation(id, location)
.then(function(id, location)
{
console.log("good");
});
};
$scope.delete = function() {
HomeFac.deleteLocation(id);
};
});
服务器端:
exports.putLocation = function(req, res) {
// Use the Beer model to find a specific beer
Location.findById(req.params.location_id, function(err, location) {
// Update the existing location
location.name = req.body.name;
location.category = req.body.category;
location.latitude = req.body.latitude;
location.longitude = req.body.longitude;
// Save the beer and check for errors
location.save(function(err, location) {
if (err) {
res.send(err)
};
res.json(location);
});
});
};
HomeFac更新功能
_LocationService.updateLocation = function(_id, location) {
return $http.put(urlBase + '/' + _id, location);
};
Mongoose返回的是“ Mongoose文档”,而不是标准的JSON对象,因此,如果要更新的属性不在Schema中,则不会将它们添加到位置文档中。
如果您要做的只是更新文档,则无需先调用findById。 您可以执行Update查询,因此请传递_id来查找,然后传递一个update对象。 这将更新现有文档
exports.putLocation = function(req, res) {
var query = { _id: req.body.location_id };
var update = {
$set: {
name: req.body.name,
category: req.body.category,
latitude: req.body.latitude,
longitude: req.body.longitude
}
};
Location.update(query, update, function (err, location) {
if (err) {
return res.send(err);
}
res.json(location);
});
};
只是想出了解决方案。 我必须在客户端和服务器端修改控制器。 在服务器端,我正在使用findByIdAndUpdate进行操作。 为了使那些可能遇到此问题的人受益,我在下面发布了我的代码。
服务器端:
exports.putLocation = function(req, res) {
// Use the Location model to find a specific location
Location.findByIdAndUpdate(req.params.location_id, req.body,
function(err, location) {
if (err)
res.send(err);
res.json({ data: location });
});
};
客户控制器
.controller('UpdateCtrl', function($state, $stateParams, $rootScope, $scope, HomeFac) {
id = $stateParams.id;
$scope.location = {};
HomeFac.getLocation(id).success(function(data) {
$scope.location = data;
});
$scope.edit = function() {
name = $scope.location.name;
cat = $scope.location.category;
lat = $scope.location.latitude;
long = $scope.location.longitude;
mark = { name: name, category: cat, latitude: lat, longitude: long };
setmark = angular.toJson(mark);
HomeFac.updateLocation(id, setmark);
}
$scope.delete = function() {
HomeFac.deleteLocation(id);
$state.go('home');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.