Jessica Illy Jessica Illy - 1 month ago 19
Node.js Question

Using async with mongoose controllers/models

I can put every model within the callback of model but that kind of messy and hard to read. I found a npm called async but I have no idea how to use it.

User.find({
"email":req.body.user_email
}),
function(err,response){
if(!err){
res.json(response);
}
})

AnotherModel.find(),
function(err,response){
if(!err){
res.json(response);
}
})


I've read the doc but I don't understand it.

async.parallel([
function(callback){ ... },
function(callback){ ... }
], function(err, results) {
// optional callback
};


What i want is in the end I just have to do ONE res.json after I merge data from multiple models and send it to the front end.

Answer

Use it like this

async.parallel([
  function(callback) {
    User.find({
        "email": req.body.user_email
      }),
      function(err, response) {
        if (!err) {
          callback(null,response)
        }
      })
},
function(callback) {
  AnotherModel.find(),
    function(err, response) {
      if (!err) {
        callback(null,response)
    })

}],
function(err, results) {
  if(!err){
    res.json(results);
  // You will get array of results in your results agrs
  }
};