我创建了一个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);
});
}
});
}
})
答案 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"});
});
});
}
})