循环数据时如何使用多个callback

我试图获取HTML表单数据,通过循环,改变一下,并将其插入数据库。 我已经尝试像下面的app.js.

我怎样才能做callback,使formdata我修改了.create函数?

我从各处search,总是以某种方式结束了死胡同和未定义的variables。

app.js:

//Find the day where to save Day.findById(req.params.id, function(err, day) { if (err) { console.log(err); res.redirect("/diary"); } else { // Search function to find data with _id function ingredientIdQuery(reqBodyId) { var ingQuery = Ingredient.find({_id:reqBodyId}); return dbQuery; } // This loops through HTML formdata and formats it for mongoose model for (var i = 0; i < 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 the query for the data I need with id query.exec(function(err, ingr){ if(err) { return console.log(err); } else { singleMealTempObj.ingredient = ingr[0]; singleMealTempArr.push(singleMealTempObj); } }); } } } // This inserts data into 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"); } }); }); }); 

编辑:感谢您的回复和通知! 当我试图做所有的事情来完成这个工作时,我错过了像声明variables那样的一些东西。 对不起。 此时我把毛巾扔进笼子里。

stream程如下所示:用户将HTML表单数据发送到两个数组(id []和amount [])的对象内的app.js。 如果数组的值不等于0,则数组数组需要循环。相同的索引id数组值用于从数据库中获取数据。 这个数据是从ID [id]的数据库中find的,使用了相同的索引量[],它应该被保存到mongo中。

我可以从HTML表单中获取值。 但我曾尝试在for循环(代码中的query.exec)searchMongo中,我得到的数据好吧。 当我在数据库查询之外logging数据时,variables是未定义的。

我希望这能澄清一点,我试图实现。

我会在稍后继续… 🙂

我猜问题是由于这个function而产生的。

 function ingredientIdQuery(reqBodyId) { var ingQuery = Ingredient.find({_id:reqBodyId}); return dbQuery; } 

查找函数是asynchronous的还是同步的? 您也正在返回dbquery,但dbquery似乎并没有改变内function。

夫妇我注意到可能会解决这个问题:

  1. 你永远不会定义singleMealTempArr,所以当你试图将数据推送到它时,你会遇到问题。
  2. 您的ingredientIdQuery函数返回dbquery – 也没有定义。 你实际上称它为ingQuery。 即使如此…你是否肯定会返回你想要的数据呢?

 // lets loop through all the form fields in req.body.amount for (var i = 0; i < req.body.amount.length; i++) { // keep going unless the form field is empty if (req.body.amount[i] !== "") { // assign all the form fields to the following vars var amount = Number(req.body.amount[i]); var singleMealTempObj = {}; singleMealTempObj.amount = amount; var _id = req.body.id[i]; var query = ingredientIdQuery(_id); // we are executing the ingredientIdQuery(_id), better // double-check that this query returns the result we are // looking for! query.exec(function(err, ingr){ if(err) { return console.log(err); } else { singleMealTempObj.ingredient = ingr[0]; // now that we've gone through and mapped all the form // data we can assign it to the singleMealTempArr // WOOPS! Looks like we forgot to assign it! singleMealTempArr.push(singleMealTempObj); } }); } } }