[英]Combining two async results from MongoDB collection in NodeJS
我確定這是之前被問到的,但是由於某種原因,我無法使其工作。 最近剛開始在Mongoose中使用NodeJS(習慣於異步處理所有事情)我要實現的目的之一是根據某種邏輯將來自兩個不同集合的兩個結果組合在一起。
因此,假設我具有此get函數,則應異步獲取所有技能(例如),然后從另一個集合中獲取所有特定的用戶技能,並將它們組合為一組結果,這將添加一個“ isSelected:true在userSkills集合中找到該屬性。 這是用ES6編寫的:
exports.get = (req, res) => {
const combineSkills = (allSkills)=>{
const { userid } = req.headers;
return UserSkills.GetUserSkills(userid).then((response)=>{
for(var i=0;i<=response.length-1;i++){
var userSkill = response[i];
var found = allSkills.filter(e=>e.id==userSkill.skillId);
if(found.length>0){
found.isSelected=true;
}
}
return allSkills;
});
}
const respond = (response) => {
res.json({
ReturnCode: 2,
ReturnObject: response
})
}
// error occured
const onError = (error) => {
res.status(403).json({
ReturnCode: 0,
ReturnObject: error.message
})
}
Skills.GetAll()
.then(combineSkills)
.then(respond)
.catch(onError)
}
如您所見,我試圖調用Skills.GetAll()技能,然后將結果獲取到CombineSkills對象,執行一些邏輯並返回新對象。 我知道我的問題出在CombineSkills函數中,其中的return語句在邏輯更改之前返回對象。
我的問題是在這種情況下正確的語法是什么?
filter
函數返回一個數組,您必須使用以下find
方法返回所需的技能:
const combineSkills = (allSkills) => {
const { userid } = req.headers;
return UserSkills.GetUserSkills(userid).then((response) => {
for (var i = 0; i <= response.length - 1; i++) {
var userSkill = response[i];
var found = allSkills.find(e => e.id == userSkill.skillId);
if (found) {
found.isSelected = true;
}
}
return allSkills;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.