Codemiester Codemiester - 3 months ago 13
Node.js Question

Mongoose, Angular, Express PUT won't work

I am trying to implement a simple edit function, and it won't work. My delete and get do work. I keep getting a 500 error on the put request. I have tried findIdAndUpdate and I hace tried FindOne as well. The error I get, is it fails to load the resource. But if I do a get request it works fine. If this makes a difference, the get request also returns a 304.

If I send the request in curl I get

TypeError: Cannot read property 'id'


Controller and Service

app.factory('gameService', function($resource){
return $resource('/api/games/:id', {id:'@id'},
{'update': {method:'PUT'}}
);
});

app.controller("gameController", function($scope, $http, gameService){
$scope.games = [];
$scope.newGame = {name: '', platform: ''};
$scope.editMode = false;

$scope.games = gameService.query();

$scope.edit = function(game){
$scope.editMode = true;
$scope.newGame = gameService.get({id: game._id});
};

$scope.update = function(){
gameService.update({id: $scope.newGame._id}, function(response){
$scope.games = gameService.query();
$scope.newGame = {name: '', platform:''};
});
$scope.editMode = false;
};
});


API/Express/Mongoose

router.put('/games/:id', function(req, res, next) {
Game.findById(req.parms.id, function (err, game) {
if (err) {
return res.send(err);
}
game.name = req.body.name;
game.platform = req.body.platform;
game.save(function(err){
if (err) {
return res.send(err);
}
res.json({message:'Game Updated'});
});
});
});


HTML

<input required type="text" placeholder="Game Name" ng-model="newGame.name" /> <br/><br/>
<input required type="text" placeholder="Platform" ng-model="newGame.platform" /> <br/><br/>
<input class="button" type="submit" value="Post" ng-click="post()" ng-hide="editMode" />
<input class="button" type="submit" value="Update" ng-click="update()" ng-show="editMode"/>


Model

var mongoose = require ('mongoose');
var GameSchema = new mongoose.Schema({
name: String,
platform: String
});

mongoose.model ('Game', GameSchema);

Answer

req.parms.id should be req.params.id in your Mongoose/Express API route.

Comments