让我们考虑维护各种类型得分的字典,比如{a:0,b:0,c:0}我有3个mongo db A,B和C集合表演,
A.find({<key>:<value>})
.then(res=>{
//gets an array of the response <RES1>
})
现在对于数组中的每个元素,我都是这样做的
B.find({_id : <RES1[i].some_id>})
.then(res=>{
//again a new array of responses <RES2>
})
最后,我得到了需要在集合C中更新分数的类型,我再次在循环中查询
C.find({_id : RES2[i].some_key})....
我不确定我错在哪里!嵌入代码如下
getScoreForEachTypes() {
User.find({ company: req.params.company })
.then(users => {
var responsesOfAllUsersArr = [];
usersForThisCompany = users;
users.forEach(user => {
responsesOfAllUsersArr.push(Response.find({ email: user.email }));
});
return Promise.all(responsesOfAllUsersArr);
})
.then(responsesOfAllUsersArr => {
var data = { _E: 0, _M: 0, _A: 0, _Q: 0, _E: 0 };
responsesOfAllUsersArr.forEach(el => {
el.forEach(_el => {
var j = getQuestionType(_el.questionId);
data[j] += _el.responseChoice;
})
})
});
}
function getQuestionType(qid) {
return Question.findOne({ _id: qid })
.then(el => {
return el.quesType;
})
.catch(err => {
console.log("err while fetching type of question", err);
});
}
最后我解决了我的问题。我只需要维护一个数组。
function a(){
var data = { PE: 0, RM: 0, BA: 0, AIQ: 0, FE: 0 };
var responsesAll = [];
var xyz = [];
return User.find({ company: req.params.company })
.then(users => {
var responsesOfAllUsersArr = [];
usersForThisCompany = users;
users.forEach(user => {
responsesOfAllUsersArr.push(Response.find({ email: user.email
}));
});
return Promise.all(responsesOfAllUsersArr);
})
.then(responsesOfAllUsersArr => {
responsesOfAllUsersArr.forEach(el => {
el.forEach(_el => {
responsesAll.push(_el);
xyz.push(getQuestionType(_el.questionId))
})
})
return Promise.all(xyz);
}).then(xyz => {
for (var i = 0; i < xyz.length; i++) {
data[xyz[i].quesType] += parseInt(responsesAll[i].responseChoice);
}
return data;
})
}