0

I am trying to combine the result of two functions calls and return a json object as the output to my api call.

getUserList function retries the list of registered users and averageUserAge function returns the average age of people belongs to a particular age group

In merge function i want to combine the output of both and return a json object.

Can some one explain how can i achieve this?

Please note that i am not looking for aggregate function as it doesn't yield the expected output in my business case.Below is the sample code written to demonstrate what i am looking for as my business case too complex to explain.

function getUserList(req,res){

userModel.findOne({ageGroup : 'some group'},{name : 1,email : 1, credits : 1},{}, function(err, result) {
    if( err || !result) {
        console.log("No user found");
    } else {
        return result
    };
});

}

function averageUserAge(req,res) {

ageModel.findOne({ageGroup : 'some group'},{email : 1, credits : 1},{}, 
function(err, result) {
    if( err || !docs) {
        console.log("No users with a particular age group found");
    } else {
        return result
    };
});

}
//Merge the output of two function calls
function merge(req,res){

   var result1=getUserList(req,res)
   var result2=averageUserAge(req,res)

   var mergedResult=//How to merge result1 & result2

   return res.json(mergedResult)

}
Sona Shetty
  • 997
  • 3
  • 18
  • 41
  • Possible duplicate of [combine or merge json object](https://stackoverflow.com/questions/14974864/combine-or-merge-json-on-node-js-without-jquery) – Basheer Kharoti Oct 03 '17 at 09:57
  • Refer this answer https://stackoverflow.com/a/45728310/7635845 actually this answer is related to mysqldb and in the place of mysql queries keep mongodb queries and check .This code works for me I hope this helps you in mongodb also.. – Syed Ayesha Bebe Oct 03 '17 at 10:33

2 Answers2

1

you can use this awesome library async Or you can use callbacks

Riyaz Shaikh
  • 141
  • 9
0

You could try something like this:

function merge(req, res) {
    const result1 = getUserList(req,res);
    const result2 = averageUserAge(req,res);

    return Promise.all([result1, result2]).then(() => {
        return res.send({res1: result1, res2: result2});
    }).catch(e => res.status(400).send(e));
};

Promise.all makes sure that result1 and result2 have returned their values respectively. Then you send back a response containing a JSON object including your res1 and res2 results.

OArnarsson
  • 801
  • 1
  • 9
  • 25