简体   繁体   中英

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.

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. This is written in 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. I know my problem is in the combineSkills function, where my return statement returns the object before the logic change.

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 :

  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;
      });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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