为什么我的Mongoose delete命令返回空响应?

时间:2016-03-22 00:35:07

标签: javascript node.js mongodb mongoose

我创建了一个JavaScript删除函数,它从MongoDB数据库中删除数据。问题是响应是空的。知道为什么会这样,以及我如何解决这个问题?我需要让案例1工作......

响应为空(1):

.delete(function(req, res) {
        var response = {};
        if (password == req.body.token) {
            mongoOp.findById(req.params.id, function(err, data) {
                if (err) {
                    response = {"error": true, "message": "Error fetching data"};
                } else {
                    mongoOp.remove({_id: req.params.id}, function(err) {
                        if (err) {
                            response = {"error": true, "message": "Error deleting data"};
                        } else {
                            response = {"error": true, "message": "Data associated with " + req.params.id + "is deleted"};
                        }                     
                    });
                } 
                res.json(response);               
            });
        }        
    })

响应不为空(2):

.delete(function(req, res) {
        var response = {};
        if (password == req.body.token) {
            mongoOp.findById(req.params.id, function(err, data) {
                if (err) {
                    response = {"error": true, "message": "Error fetching data"};
                } else {
                    mongoOp.remove({_id: req.params.id}, function(err) {
                        if (err) {
                            response = {"error": true, "message": "Error deleting data"};
                        } else {
                            response = {"error": true, "message": "Data associated with " + req.params.id + "is deleted"};
                        }
                        res.json(response);                     
                    });
                }               
            });
        }        
    })

1 个答案:

答案 0 :(得分:1)

这是因为回调:第一种情况下res.json(response);mongoOp.remove调用它的回调function(err) { ...之前被调用。

Node.js是异步的。

UPD: 最好不要在这里使用临时变量response和额外的if

.delete(function(req, res) {
    if (password == req.body.token) {
        mongoOp.findById(req.params.id, function(err, data) {
            if (err) {
                return res.json({"error": true, "message": "Error fetching data"});
            }
                mongoOp.remove({_id: req.params.id}, function(err) {
                    if (err) {
                        return res.json({"error": true, "message": "Error deleting data"});
                    }
                        return res.json({"error": true, "message": "Data associated with " + req.params.id + "is deleted"});
                });             
        });
    }        
})