简体   繁体   English

在NodeJS中组合来自MongoDB集合的两个异步结果

[英]Combining two async results from MongoDB collection in NodeJS

I'm sure this was asked before, but for some reason I am not able to make it work. 我确定这是之前被问到的,但是由于某种原因,我无法使其工作。 Started using NodeJS with Mongoose just lately (getting used to doing everything async) One of the things I'm trying to achieve is combining two results from two different collections according to some logic. 最近刚开始在Mongoose中使用NodeJS(习惯于异步处理所有事情)我要实现的目的之一是根据某种逻辑将来自两个不同集合的两个结果组合在一起。

So assuming I have this get function, it should go fetch asynchronously all skills (for example), then from another collection, i should fetch all specific user skills, and combine them into one set of results, which will add a "isSelected:true" property when it's found in the userSkills collection. 因此,假设我具有此get函数,则应异步获取所有技能(例如),然后从另一个集合中获取所有特定的用户技能,并将它们组合为一组结果,这将添加一个“ isSelected:true在userSkills集合中找到该属性。 This is written in ES6: 这是用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)

} }

As you can see, I'm trying to call Skills.GetAll() skills, then get results to combineSkills object, do some logic and return the new object. 如您所见,我试图调用Skills.GetAll()技能,然后将结果获取到CombineSkills对象,执行一些逻辑并返回新对象。 I know my problem is in the combineSkills function, where my return statement returns the object before the logic change. 我知道我的问题出在CombineSkills函数中,其中的return语句在逻辑更改之前返回对象。

My question is what is the right syntax for such scenario? 我的问题是在这种情况下正确的语法是什么?

filter function return an array, you have to return the needed skills using find method like : 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM