如何在节点中进行异步回调并确保 HTML 表单数据可用于保存到数据库

达米

如何制作回调和变量,以便将数据保存到我的数据库?

我有如下所示的节点 app.post。我需要将表单数据转换为猫鼬模型。我得到的数据在两个数组中,只有数量大于 0 的数据才会被搜索和保存,但这不起作用,我无法绕过它。

我认为循环和搜索成分应该是一个函数,而 Meal.save 应该在回调中,但我不知道如何。几个星期以来,我一直在思考这个问题,我已经用谷歌搜索过了,但这对我来说并不开放。请帮我解决一下这个。

提前致谢!

应用程序.js

app.post("/diary/:id/dayshow", function(req, res) {

// Get the day I want to save my meal data
  Day.findById(req.params.id, function(err, day) {
    if (err) {
      console.log(err);
      res.redirect("/diary");
    } else {

// This is the format I have in the mongoose model
// and I need to convert HTML form data to this

        var singleMeal =
          {
          //       title: dinner
          //       ingredients: [
          //                      {
          //                        ingredient:{},
          //                        amount: Number
          //                      }
          //                    ]
          }
        var singleMealTempArr = [];
        var singleIngredientObj = {};
        var amount;
        singleMeal.title = req.body.title;

// Looping through the HTML form data and converting it to mongoose model
// I want to loop data and search mongo first and after that I need to save 
// the data to mongo which happens in Meal.save()

        for (var i = 0; i < req.body.amount.length; i++) {
          var _id = req.body.id[i];
          amount = Number(req.body.amount[i]);
          if (amount !== 0) {
            singleIngredientObj.amount = amount;

// Searching ingredient from database with ID what is from the HTML form

            Ingredient.findById({_id}, function(err, foundIngredientData){
              console.log(foundIngredientData + "<<<<<<<<<<<<< ingredientData");
              singleIngredientObj.ingredient = foundIngredientData;
              singleMealTempArr.push(singleIngredientObj);
              console.log(JSON.stringify(singleMealTempArr) + "<<<<<<<<<<<< JSON.stringify(singleMealTempArr)");
            });
          }
        }
        singleMeal.ingredients = singleMealTempArr;

 // Now I should have data in singleMeal variable, but it has only title and 
 // empty array of ingredients
        console.log("JSON.stringify(singleMeal) >>>>>>>>>" + JSON.stringify(singleMeal) + "<<<<< JSON.stringify(singleMeal)");
      }

       Meal.create(singleMeal, function(err, singleMealObject) {
        if (err) {
          console.log(err);
        } else {
      console.log("--- You hit the Meal.create + Save -----" + "singleMealObject: " + singleMealObject);
        //  day.meals.push(singleMealObject);  <-- These two are commented because previous steps dont work and singleMealObject has only title and empty array of ingredients
        //  day.save();

          res.redirect("/diary/" + day._id + "/dayshow");
        }
      });
  });
});

我从上面得到的 console.logs 在这里:

JSON.stringify(singleMeal) >>>>>>>>>{"title":"aa","ingredients":[]}  <<<<< JSON.stringify(singleMeal)

{ _id: 597c11c04a7bce08cdcdef41,
  name: 'oatmeal',
  kcal: 100,
  protein: 2,
  carb: 50,
  fat: 1,
  addinfo: '',
  __v: 0 }  <<<<<<<<<<<<< ingredientData

[{"amount":3,"ingredient":{"_id":"597c11c04a7bce08cdcdef41","name":"oatmeal","kcal":100,"protein":2,"carb":50,"fat":1,"addinfo":"","__v":0}}]  <<<<<<<<<<<< JSON.stringify(singleMealTempArr)

{ _id: 597c11c04a7bce08cdcdef41,
  name: 'oatmeal',
  kcal: 100,
  protein: 2,
  carb: 50,
  fat: 1,
  addinfo: '',
  __v: 0 } <<<<<<<<<<<<< ingredientData

[{"amount":3,"ingredient":{"_id":"597c11c04a7bce08cdcdef41","name":"oatmeal","kcal":100,"protein":2,"carb":50,"fat":1,"addinfo":"","__v":0}},{"amount":3,"ingredient":{"_id":"597c11c04a7bce08cdcdef41","name":"oatmeal","kcal":100,"protein":2,"carb":50,"fat":1,"addinfo":"","__v":0}}]<<<<<<<<<<<< JSON.stringify(singleMealTempArr)

--- You hit the Meal.create + Save -----singleMealObject: { __v: 0,
  title: 'aa',
  _id: 597c11cb4a7bce08cdcdef61,
  ingredients: [] }
帽子

您可以查看此 stackoverflow 答案以获取与 ID 相关的记录。mongodb/mongoose findMany - 查找 ID 列在数组中的所有文档

app.post("/diary/:id/dayshow", function(req, res) {

// Get the day I want to save my meal data
  Day.findById(req.params.id, function(err, day) {
    if (err) {
      console.log(err);
      res.redirect("/diary");
    } else {

// This is the format I have in the mongoose model
// and I need to convert HTML form data to this

        var singleMeal =
          {
          //       title: dinner
          //       ingredients: [
          //                      {
          //                        ingredient:{},
          //                        amount: Number
          //                      }
          //                    ]
          }
        var singleMealTempArr = [];
        var amount;
        singleMeal.title = req.body.title;


        function generateMeal(callback) {

            var meal_ids = [];
            for (var i = 0; i < req.body.amount.length; i++) {
                  var singleIngredientObj = {};
                  var _id = req.body.id[i];
                  amount = Number(req.body.amount[i]);
                  if (amount !== 0) {
                    meal_ids.push(_id);
                    singleIngredientObj.amount = amount;
                    singleMealTempArr.push(singleIngredientObj);
                  }

            }

            Ingredient.find({_id : meal_ids}, function(err, getIngredientsOfIds){
                 // not added amount. you can do it data massage whatever you want
                  if(err) {
                    //error handling
                    return;
                  }
                  for(var i = 0; i < singleMealTempArr.length; i++) {
                    singleMealTempArr[i].ingredients = getIngredientsOfIds[i];  
                  }
                  singleMeal.ingredients  =  singleMealTempArr;
                  callback();
            });

        }



        function createMeal() {
             Meal.create(singleMeal, function(err, singleMealObject) {
                if (err) {
                  console.log(err);
                } else {
              console.log("--- You hit the Meal.create + Save -----" + "singleMealObject: " + singleMealObject);
                //  day.meals.push(singleMealObject);  <-- These two are commented because previous steps dont work and singleMealObject has only title and empty array of ingredients
                //  day.save();

                  res.redirect("/diary/" + day._id + "/dayshow");
                }
              });
        }

        generateMeal(createMeal);

      });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

保存到数据库时如何转义html?

将新的表单数据保存回数据库

如何在数据库中存储不同种类和数量的html表单数据?

'将HTML表单数据保存在数据库中'Django

HTML表单数据未保存在数据库中-Django

如何将HTML5,经度和纬度保存到数据库中?

如何使用 JAVA 将图像从 HTML 保存到数据库

如何从HTML页面创建PNG图像并将其使用Django保存到数据库中?

Laravel 如何将 HTML 保存到数据库然后检索它

如何在MySQL数据库的许多行中保存表单数据(表单内的表)

将HTML表单数据保存到本地存储

将 HTML 表单数据保存到 Google Sheet

将html表单数据保存到文件

检索HTML动态表单字段数据并保存到MySQL数据库

PHP SQL:如何从一个html表单将数据保存到多个数据库,或者如何自动将数据从一个数据库复制到另一个数据库

如何在PHP / HTML中进行客户端表单数据验证

将Ckeditor编辑器元素保存到数据库中后,如何在html中设置其格式?

如何在使用 django 按下 html 按钮时将布尔值保存到数据库中

动态HTML表单并保存到数据库的多个记录中

在show.html.erb中使用简单表单(嵌套表单)不会将数据保存到数据库

HTML标签作为HTML实体保存到数据库

如何根据表单数据更新数据库

如何在数据库中保存HTML

如何保存到 Firebase 数据库?

如何在 Django 中从 base.html 保存表单数据?

如何从html表单访问javascript数据库?

如何获取简单的HTML表单以发布到数据库

如何在表单中将Json发布到控制器然后保存到数据库

@ Html.Dropdownlist列表未保存到数据库