Trouble with PUT request using Node.js (express), Angular, and MongoDB

一曲冷凌霜 提交于 2019-12-01 00:41:10

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.

You have to do like:

model:

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

controller:

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

route:

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

take a look at

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

BTW

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

should be

.success(function(data) {
            $scope.habitList = data.data;
            console.log(data.data);
        })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!