从HTML表单中提取数据并将其保存在MongoDB中

时间:2017-07-22 09:49:24

标签: javascript html node.js forms express

如何从HTML表单中获取数据并使用node和express保存MongoDB?目前,我无法以我的模型所需的格式获取数据。你能帮我找到我失踪的东西吗?如果有不明白的词,请不要介意。我把它翻译成英文。

在HTML I文件中有两个输入字段:我需要组合在一起的成分和数量。该组输入在页面中存在10次。

<form action="/diary/<%= day._id %>/showday" method="post" name="meal">
        <div class="">
          <input type="text" name="meal[title]" value="">
        </div>
        <% for(i = 0; i<10; i++) { %>    
        <div>
          <fieldset>
            <select name="meal[ingredients]">
              <% ingredients.forEach(function(singleIngredient){ %>
                  <option value="<%= singleIngredient %>" name="<%= singleIngredient %>"><%= singleIngredient.aine %></option>
            <%  }); %>
            </select>
            <input type="number" name="meal[amount]" placeholder="gr">
          </fieldset>
        </div>
        <% } %>
        <div>
          <button>Submit!</button>
        </div>
</form>

我从表单中获得的数据是两个数组,无论我尝试过什么,我都无法正确格式化。我也试过过fieldset标签,但它并没有改变数据的格式。

我有如下的Mongoose模型:

ingredient.js
var mongoose = mongoose = require("mongoose");
var ingredientSchema = mongoose.Schema({
  ingredient: String,
  kcal: Number,
  protein: Number,
  carbs: Number,
  fat: Number,
  addinfo: String
});
module.exports = mongoose.model("Ingredient", ingredientSchema);

meals.js
var mongoose = require("mongoose");
const Ingredient = require('../models/ingredient');
var mealSchema = mongoose.Schema({
  title: String,
  ingredients: [{ingredient: Ingredient.schema, amount: Number}],
});
module.exports = mongoose.model("Meal", mealSchema);

day.js
var mongoose = mongoose = require("mongoose");
const Meal = require('../models/meal');
var daySchema = mongoose.Schema({
  day: Date,
  meals: [Meal.schema]
});
module.exports = mongoose.model("Day", daySchema);

app.js如下所示。在app.js中,我尝试将表单数据放入模型的格式中,但是当我记录结果时,它看起来与种子数据有点不同,我认为这就是为什么这不起作用的原因

Day.findById(req.params.id, function(err, day) {
if (err) {
  console.log(err);
  res.redirect("/diary");
} else {
  var singleMeal = [];
  var singleIngredient = {};
  var singleIngredientArray = [];
  var singleIngredientAmount = "";

  var len = req.body.meal.amount.length;
  for (i=0; i < len; i++) {

//MODIFY DATA SO THAT ITS IN RIGHT FORMAT AND TAKE ONLY INGREDIENTS WHICH HAS AMOUNT ABOVE 0
    if (req.body.meal.amount[i] !== "") {
      singleIngredient.ingredient = req.body.meal.ingredient[i];
      singleIngredient.amount = Number(req.body.meal.amount[i]);
      singleIngredientArray.push(singleIngredient);
singleMeal.push(singleIngredientArray[i]);
console.log(singleIngredient.ingredient + "<<<< ==== singleIngredient.ingredient");
console.log(singleIngredientArray);
console.log(singleMeal[i].title + "<<<< ==== singleMeal.title");
//--- THIS IS WHERE THE GAME ENDS ----
        } else {
        }
      }         
Meal.create(singleMeal, function(err, meal) {
            if (err) {
              console.log(err);
            } else {
              day.meals.push(meal);
              day.save();
              res.redirect("/diary/" + day._id + "/showday");
            }
          });
        };
      });
    });

当我在app.js中记录时,这是我在控制台中获得的:

[object Object]<<<< ==== singleIngredientArray
{ _id: 59731a5156809d5ee310aad0,
  ingredient: 'Kaurahiutale',
  kcal: 100,
  protein: 2,
  carb: 50,
  fat: 1,
  addinfo: '',
  __v: 0 }<<<< ==== singleIngredient.ingredient
undefined<<<< ==== singleMeal[i].title

有时当我尝试别的东西(甚至不记得因为我已经尝试过除了正确的方式之外的几乎所有东西)之后我也有了这样的结果,如下所示,但它有\ r \ n字符,它看起来有点与种子数据不同。

{ ingredient: '{ _id: 59731357eee39a59fb5a5878,\r\n  ingredient: \'oatmeal\',\r\n  kcal: 100,\r\n  protein: 2,\r\n  carb: 50,\r\n  fat: 1,\r\n  addinfo: \'fineli.fi\',\r\n  __v: 0 }',
  amount: 3 }
{ ingredient: '{ _id: 59731357eee39a59fb5a5878,\r\n  ingredient: \'oatmeal\',\r\n  kcal: 100,\r\n  protein: 2,\r\n  carb: 50,\r\n  fat: 1,\r\n  addinfo: \'fineli.fi\',\r\n  __v: 0 }',
  amount: 3 }

当我启动应用程序时,这个种子数据被加载到Mongo并且它正常工作。 seed.js:

    var ingredients = [
  {
    ingredient: "oatmeal",
    kcal: 100,
    protein: 2,
    carb: 50,
    fat: 1,
    addinfo: ""
  },

  {
    ingredient: "Whey80",
    kcal: 150,
    protein: 80,
    carb: 2,
    fat: 1,
    addinfo: ""
  },
  {
    ingredient: "Tomato",
    kcal: 20,
    protein: 1,
    carb: 4,
    fat: 0,
    addinfo: ""
  }
];

var meals = [{
    title: "Breakfast",
    ingredients: [{ingredient: ingredients[1], amount: 5}]},
  {
  title: "Some snack",
  ingredients: [{
    ingredient: {
        ingredient: "Whey80",
        kcal: 150,
        protein: 80,
        carb: 4,
        fat: 0,
        addinfo: ""
      },
    amount: 40},
    {
      ingredient: {
ingredient: "Whey80",
          kcal: 150,
          protein: 80,
          carb: 4,
          fat: 0,
          addinfo: ""
      },
      amount: 40},
  ]}
];
var days = [{
  day: "010101",
  meals: [meals[0], meals[1]]
}];

如果你能指出我在哪里出错,我真的很感激。

0 个答案:

没有答案