【问题标题】:Mongoose, Angular, Express PUT won't workMongoose、Angular、Express PUT 不起作用
【发布时间】:2016-12-28 04:39:58
【问题描述】:

我正在尝试实现一个简单的编辑功能,但它不起作用。我的删除并开始工作。我在 put 请求上不断收到 500 错误。我已经尝试过 findIdAndUpdate 并且我也尝试过 FindOne。我得到的错误是它无法加载资源。但如果我做一个获取请求它工作正常。如果这有所不同,get 请求也会返回 304。

如果我在 curl 中发送请求,我会得到 TypeError: Cannot read property 'id'

控制器和服务

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"/>

型号

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

mongoose.model ('Game', GameSchema);

【问题讨论】:

    标签: angularjs node.js mongodb express mongoose


    【解决方案1】:

    req.parms.id 在您的 Mongoose/Express API 路由中应该是 req.params.id

    【讨论】:

    • 修复了这个问题。现在我有一个新问题。 game.save 正在清除 name 和 platofmr 字段。所以看起来 req.body.name 不正确
    猜你喜欢
    • 2015-07-16
    • 2021-05-26
    • 1970-01-01
    • 2017-07-17
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2017-03-08
    相关资源
    最近更新 更多