node.js - Mongoose Async Call Issue with Find Query -
i have var movierecommendation
being populated data coming mongo db. issue mongoose movie.findone()
call asycn call not allowing me final populated movierecommendation
need send response.
exports.getrecommendation=function(req,res){ var movierecommendation = []; var id=req.params.id; console.log('----- user recommendation - ' + id); var url = 'http://52.8.48.113:8080/recommender-server/recommender/v1/recommendations/'+id+'.do'; //make http request request({ url: url, json: true }, function (error, response, recommendations) { // res.json(recommendations); if (!error && response.statuscode === 200) { recommendations.foreach(function(entry) { **movie.findone({'id':parseint(entry.itemid)},function(err, moviedata){** entry.movie = moviedata; movierecommendation.push(entry); //console.log('rec', movierecommendation); console.log(movierecommendation.length); }); }); } console.log("====final========"+movierecommendation.length); //output = 0 }); res.json(movierecommendation); // here movierecommendation coming black array };
please let me know how can populated movierecommendation
var @ end make available response.
for type of issues can use async library. populate data once operations done, can use async.each collection async library.
for example: note:install async command npm install async use async library
var async = require("async"); var recomenmendations = [{"data2" : "value2"} , {"data1" : "value2"}, {"data3" : "value3"}, {"data4" : "value4"} ] var movierecommendation = []; async.each(recomenmendations, function(recomenmendationitem, callback){ console.log("here can query required data using current recomenmendations item"); console.log(recomenmendationitem); callback(); // movie.find({'id':parseint(recomenmendationitem.itemid)},function(err, moviedata){ // recomenmendationitem.movie = moviedata; // movierecommendation.push(entry); // callback(); // }); }, function(err){ console.log("here can send resopnse"); console.log("this section executed once recomenmendations processed"); //res.json(movierecommendation) } );
you can query mongodb shown comment section. should use callback() once operations performed iteration.
Comments
Post a Comment