我试图获取HTML表单数据,将其循环,稍微更改并将其插入数据库。我试过下面的app.js。
如何进行回调,以便我修改的formdata可用于.create函数?
我从各处搜索过,我总是以某种方式结束死胡同和未定义的变量。
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");
}
});
});
});
编辑: 感谢您的回复和通知!当我试图做所有事情来完成这项工作时,我错过了一些事情,比如声明变量。对不起。此时我把毛巾扔进了笼子里。
流程如下: 用户将HTML表单数据发送到app.js,这是两个数组(id []和amount [])的对象内部。如果数量值不是0,则需要循环数量数组。相同的索引ID数组值用于从数据库中获取数据。从id为[id]的数据库中找到的数据与相同的索引量[]一起使用,应该保存到mongo。
我可以从HTML表单中获取值。但我试图在for循环中搜索Mongo(代码中的query.exec)我得到的数据还可以。当我在数据库查询之外记录数据时,变量是未定义的。
我希望这能澄清我想要实现的目标。
我稍后会继续......:)
答案 0 :(得分:0)
我注意到夫妇可以解决这个问题:
// 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);
}
});
}
}
}
答案 1 :(得分:0)
我猜问题源于此功能。
function ingredientIdQuery(reqBodyId) {
var ingQuery = Ingredient.find({_id:reqBodyId});
return dbQuery;
}
find函数是异步还是同步? 您还要返回dbQuery,但函数内部似乎没有更改dbQuery。