2

データを MongoDB に更新する方法を見つけようとして立ち往生しています (Monk を MongoDB、Node、Express、および Angular で使用しています)。POST と DELETE には問題はありませんが、PUT のどこが間違っているのかわかりません。

私が得るエラー:

PUT http://localhost:3000/api/habits/[object%20Object] 500 (Internal Server Error) 

私が混乱しているのは、Angularで送信する必要があるものと、ノードでそれを受信する方法です。レコードの更新されたオブジェクトを送信する必要があることを理解しているためですが、それを検索するためにIDにアクセスするにはどうすればよいですか?モンゴで?

たとえば、私の POST (以下のコード コンテキスト) では、オブジェクト「newHabitData」を送信していることは理にかなっています。

$http.post('http://localhost:3000/api/habits', newHabitData)

しかし、私が見る PUT の例では、オブジェクト (id という名前) を :parameter として送信します。

app.put('/api/articles/:id', function (req, res){

私は、PUT の使用方法を理解するのに最も近いこれらのチュートリアルを使用してきました: http://aleksandrov.ws/2013/09/12/restful-api-with-nodejs-plus-mongodb/ http:/ /scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4

アドバイスをありがとう!

角度:

// Works Fine
$scope.addHabit = function(){
    var newTitle = $scope.newTitle.trim();
    if(!newTitle){
        return;
    }
    var newHabitData = {
        title: newTitle,
        count: 0,
        status: 'active'
    };

    $http.post('http://localhost:3000/api/habits', newHabitData)
        .success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

    $('.habit-form__input-title').val('').focus();
    $scope.newTitle = '';

}

// Works Fine
$scope.habitDestroy = function (id) {       
    $http.delete('/api/habits/' + id._id)
        .success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
};

// NOT WORKING - I WANT TO INCREMENT THE COUNT, THEN SAVE
$scope.habitCheckIn = function(id){             
    id.count = ++id.count;

    $http.put('/api/habits/' + id)  // Should I be sending the entire object? Seems to make most sense to me
        .success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
}

ノード:

// Get all habits -- WORKS FINE
router.get('/api/habits', function(req, res) {
    var db = req.db;
    var collection = db.get('habits');
    collection.find({},{},function(e,data){
        res.json(data);
    });
});

// Create one habit -- WORKS FINE
router.post('/api/habits', function(req, res) {
    var db = req.db;
    var collection = db.get('habits');
    collection.find({},{},function(e,data){     
        collection.insert({ 
            title: req.body.title, 
            count: req.body.count  
        }, function(err, habit){
            if(err){
                res.send(err);
            }

            collection.find({},{},function(e,data){
                res.json(data);
            });
        });
    });
});

// Delete one habit -- WORKS FINE
router.delete('/api/habits/:habit_id', function(req, res){
    var db = req.db;
    var collection = db.get('habits');

    collection.find({},{},function(e,data){ 
        collection.remove({
            _id : req.params.habit_id
        }, function(err, todo){
            if(err){
                res.send(err);
            }

            collection.find({},{},function(e,data){
                res.json(data);
            });
        })
    })
})

// Update Habit -- NOT WORKING    
router.put('/api/habits/:habit_id', function(req, rest){
    var db = req.db;
    var collection = db.get('habits');

    // the real ID is _id, so should I be doing req.params.habit_id._id ? Or is findById asking for the entire object, and it finds the actual id itself? This is where I'm lost, can't figure it out.
    collection.findById(req.params.habit_id, function(e,data){  
        if(e){ res.send(e); }
        data.title = req.body.title;
        data.count = req.body.count;
        data.save(function(err){
            if(err){
                res.send(err);
            res.json(data);
            }
        })
    })
})

更新 - 以下のコードで動作します。 私を正しい方向に導いてくれた saintedlama に感謝します。

これが正しい方法かどうかはわかりませんが、うまくいきます。パラメータとして渡された ID ではなく、req.body 値にアクセスすることで、POST 形式に従いました。

したがって、これの代わりに:

router.put('/api/habits/:habit_id', function(req, res) {

これは私がしました:

router.put('/api/habits', function(req, res) {

次に、req.body._id と req.body.count の値を使用して、id と更新されたカウント/タイトルにアクセスしました。

router.put('/api/habits', function(req, res) {
    var db = req.db;
    var collection = db.get('habits');
    var id = req.body._id;

    if(!req.body) { 
        return res.send(400); 
    } // 6

    collection.findById(id, function(e,data){  
        if(e) { 
            return res.send(500, e); 
        } // 1, 2

        if(!data) { 
            return res.send(404); 
        } // 3

        var update = { 
            title : req.body.title, 
            count : req.body.count 
        }; // 4

        collection.updateById(id, update, function(err) { // 5
            if(err) {
                return res.send(500, err);
            }

        });
    });
});
4

2 に答える 2

0

次のようにする必要があります。

モデル:

/**
 * Statics
 */
PostSchema.statics.load = function(id, cb) {
    this.findOne({
        _id: id
    }).populate('user', '_id name username email role').exec(cb);
};

コントローラ:

exports.post = function(req, res, next, id) {
    if (!/^[0-9a-fA-F]{24}$/.test(id)) {
        return res.jsonp(404,{
            error: 'Failed to load post with id ' + id
        });
    }
    Post.load(id, function(err, post) {
        if (err) {
            return next(err);
        }
        if (!post){
            return res.jsonp(404,{
                error: 'Failed to load post with id ' + id
            });
        }
        req.post = post;
        next();
    });
};

ルート:

app.put('/admin/api/post/:postId', postController.update);
 app.param('postId', postController.post);

を見てみましょう

http://expressjs.com/api#router.param

ところで

.success(function(data) {
            $scope.habitList = data;
            console.log(data);
        })

する必要があります

.success(function(data) {
            $scope.habitList = data.data;
            console.log(data.data);
        })
于 2014-08-20T15:18:38.127 に答える