使用Node.js(express),Angular和MongoDB发生PUT请求的麻烦 [英] Trouble with PUT request using Node.js (express), Angular, and MongoDB

查看:152
本文介绍了使用Node.js(express),Angular和MongoDB发生PUT请求的麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何将我的数据更新为MongoDB(我正在使用Monk与MongoDB,Node,Express和Angular)。我没有POST和DELETE的麻烦,但不能弄清楚我在哪里出错了PUT。



错误我得到:

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

困惑的是我应该用Angular发送什么,以及如何在Node中接收它,因为我明白我需要发送更新的对象进行记录,但是我该如何访问ID来查找Mongo? / p>

例如,使用我的POST(更多的代码上下文),我正在发送对象newHabitData

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

但是,使用PUT示例,我们可以看到,他们将对象(名为id)发送为:参数

  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 =数据;
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);
});
};

//不工作 - 我想增加计数,那么保存
$ scope.habitCheckIn = function(id){
id.count = ++ id.count;

$ http.put('/ api / habits /'+ id)//我应该发送整个对象吗?似乎对我来说最有意义
.success(function(data){
$ scope.habitList = data;
console.log(data);
})
.error(function(data){
console.log('Error:'+ data);
});
}

NODE:

  //获取所有习惯 -  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);
});
});

//创建一个习惯 - 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({
标题:req.body.title,
count:req.body.count
},function(err,habit){
if(err){
res.send(err );
}

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

//删除一个习惯 - 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);
});
} )
})
})

//更新习惯 - 不工作
router.put('/ api / habits /:habit_id',function ,休息){
var db = req.db;
var collection = db.get('habits');

//真正的ID是_id,所以我应该要做req.params.habit_id._id?或者是findById要求整个对象,它会发现实际的id本身?这是我失去的地方,不能弄清楚。
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让我正确的方向。



不知道这是否是正确的方法,但它是有效的。
我按照我的POST格式访问req.body值,而不是作为参数传入的id。



所以,而不是这样:

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

我这样做:

 路由器。 put('/ api / habits',function(req,res){

然后我访问了id并使用req.body._id和req.body.count值更新的计数/标题

  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);
}

});
});
});


解决方案

更新现有习惯的代码片段应该正常工作有一些小修正


  1. 运行错误时总是使用 return

  2. 始终发回状态。在这种情况下,我们将发送500

  3. 检查未找到并返回404

  4. 使用简单的更新对象。这将仅更新更新对象中包含的字段

  5. 由monk返回的mongodb文档没有保存功能,需要通过集合更新文档

  6. 检查请求是否有一个正文并发送400 - 错误请求

您可以将对象ID作为hex或ObjectId传递给 findById 在和尚文档中所述。

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

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

collection.findById(req.params.habit_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(req.pa rams.habit_id,update,function(err){// 5
if(err){
return res.send(500,err);
}

res.json(data);
});
});
});

上面的代码可以通过使用 findAndModify Monk的功能。


I'm stuck trying to figure out how to update my data to MongoDB (I'm using Monk with MongoDB, Node, Express, and Angular). I have no trouble with POST and DELETE, but can't figure out where I'm going wrong with PUT.

Error I get:

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

Where I'm confused is with what I should be sending with Angular, and how to receive it in Node, since I understand I need to send the updated object for the record, but then how should I be accessing the ID to look it up in Mongo?

For example with my POST (more code context below), it makes sense that I'm sending the object "newHabitData"

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

But with PUT examples I see, they send the object (named id) as a :parameter

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

I've been using these tutorial which is the closest I could find to understanding how to use 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

A million thanks for some advice!

ANGULAR:

// 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);
        });
}

NODE:

// 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);
            }
        })
    })
})


UPDATE - THE CODE BELOW GOT IT TO WORK. Thanks to saintedlama for getting me in the right direction.

Not sure if this is the right way to do it, but it works. I followed my POST format by accessing the req.body values, not the id passed in as a parameter.

So instead of this:

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

I did this:

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

Then I accessed the id and the updated count/title using the req.body._id and req.body.count values

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);
            }

        });
    });
});

解决方案

The code fragment to update existing habits should work just fine with some small corrections

  1. When running in an error always use return
  2. Always send a status back. In this case we'll send 500
  3. Check for not found and return 404
  4. Use simple update object. This will only update fields contained in the update object
  5. The mongodb document returned by monk has no save function, the document needs to be updated via the collection
  6. Check if the request has a body and send 400 - Bad Request

You can pass a object id as hex or ObjectId to findById as stated in the Monk docs.

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

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

    collection.findById(req.params.habit_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(req.params.habit_id, update, function(err) { // 5
            if(err) {
                return res.send(500, err);
            }

            res.json(data);
        });
    });
});

The code above can be further simplified by using the findAndModify function of Monk.

这篇关于使用Node.js(express),Angular和MongoDB发生PUT请求的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆