mardi 15 novembre 2016

Make multiple request in Mongoose

I'm trying to reach different select's from another select with MongoDB database with mongoose to redirect to Emberjs front-end.

If the text above it's not clear, look at the schema of the database:

// I already get the exam content given an id
Exam:{ 
    ...
    cllections:[{
         question: Object(Id)
    }]
    ...
}

and in the question schema it's:

 question:{
     ...
     questions: String, // I want to get this given an Id exam
     value: Number      // and this
     ...
 }

I tried to get it getting the objects id of the collections and then make a for to extract each question, and save the returned values into a json variable like this:

Test.findById(id, 'collections', function(err, collections){
   if(err)
   {
      res.send(err);
   }
   var result ={}; //json variable for the response
   // the for it's with the number of objectId's that had been found
   for(var i = 0; i < collections.collections.length; i++) 
   {
   // Send the request's to the database
      QuestionGroup.findById(collections.collections[i].id).exec(function(err, questiongroup)
      {
          if(err)
          {
             res.send(err);
          }
          // save the results in the json
          result.questiongroup = questiongroup;
      });
      // it return's {}
      console.log(result);
   }
   // also return {}
   console.log(result);
   res.json({result: result});
});

It's there a way to save the requests into a variable and return it like a json to the front end?




Aucun commentaire:

Enregistrer un commentaire