javascript - How to use multiple callbacks when looping data -


i'm trying html form data, loop through, change bit , insert database. have tried below app.js.

how can make callbacks formdata have modified available .create function?

i have searched everywhere , end in dead end , undefined variable somehow.

app.js:

//find day save  day.findbyid(req.params.id, function(err, day) {  if (err) {   console.log(err);   res.redirect("/diary"); } else {   // search function find data _id      function ingredientidquery(reqbodyid) {       var ingquery = ingredient.find({_id:reqbodyid});       return dbquery;     }   // loops through html formdata , formats mongoose model      (var = 0; < req.body.amount.length; i++) {       if (req.body.amount[i] !== "") {           var amount = number(req.body.amount[i]);           var singlemealtempobj = {};           singlemealtempobj.amount = amount;           var _id = req.body.id[i];           var query = ingredientidquery(_id);   // executing query data need id           query.exec(function(err, ingr){              if(err) {                return console.log(err);              } else {                singlemealtempobj.ingredient = ingr[0];                singlemealtemparr.push(singlemealtempobj);              }            });                  }       }     }     // inserts data day     meal.create(singlemealtemparr, function(err, singlemealobject) {     if (err) {       console.log(err);     } else {      day.meals.push(singlemealobject);      day.save();      res.redirect("/day/" + day._id + "/dayshow");     }   });  }); }); 

edit: reply , notices! while trying work missed few things declaring variables. sorry that. threw towel in cage @ point.

flow goes this: user sends html form data app.js inside object of 2 arrays (id[] , amount[]). amount array needs looped through if has value other 0. same index id array value used fetch data database. data found database id id[] used same index amount[] , should saved mongo.

i can values html form ok. have tried make search in mongo in loop (query.exec in code) data ok. when log data outside database query, variable undefined.

i hope clarifys bit i'm trying achieve.

i'll continue later... :)

i guess issue originates because of function.

function ingredientidquery(reqbodyid) {           var ingquery = ingredient.find({_id:reqbodyid});           return dbquery;  } 

is find function asynchronous or synchronous? returning dbquery dbquery not seem changed inside function.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -