【发布时间】:2018-01-17 22:05:39
【问题描述】:
我正在解决一个问题,我需要在数据库中查询选民的实例,并使用该实例更新选举,无论更新是否成功,都返回到原始函数。我的代码目前如下所示:
function addCandidatesToElection(req, res) {
let electionName = req.body.electionName;
let candidates = req.body.candidates;
let addedCandidatesSucessfully = true;
for(let i=0; i<candidates.length; i++) {
addedCandidatesSucessfully = _addCandidateToElection(electionName, candidates[i]);
console.log("added candidates sucessfully:" + addedCandidatesSucessfully);
}
if(addedCandidatesSucessfully) {
res.send("createElection success");
} else {
res.send("createElection fail");
}
}
调用这个函数:
function _addCandidateToElection(electionName, candidateName) {
async.parallel(
{
voter: function(callback) {
Voter.findOne({ 'name' : candidateName }, function(err,voter) {
callback(err, voter);
});
}
},
function(e, r) {
if(r.voter === null){
return 'Voter not found';
} else {
Election.findOneAndUpdate(
{'name': electionName },
{$push: { candidates: r.voter }},
{new: true},
function(err, election) {
if(err){ return err; }
return (election) ? true : false;
});
}
}
);
}
我已经尝试打印出 Voter 实例 (r.voter) 以检查它是否存在(确实存在),并打印出由 mongoose 调用返回的选举对象,这也有效。但是,我在
中得到了一个空值addedCandidatesSucessfully = _addCandidateToElection(electionName, candidates[i]);
line,不管调用的结果如何。我认为这与 mongoose 调用返回一个本地值有关,该值永远不会返回到调用 _addCandidateToElection 的函数中,但我不知道应该如何返回它。我尝试过放置控制标志,例如
let foundAndUpdatedElection = false;
在 _addCandidateToElection 的第一行并在 Mongoose 查询的回调中更新它,但显然它没有改变。 如何将查询结果返回给 addCandidatesToElection 函数?
【问题讨论】:
标签: node.js mongodb express mongoose async.js