首页 文章

Meteor:检索和插入子文档

提问于
浏览
0

我似乎无法获取成分数组的数据并插入到mongodb中 . 有人有主意吗?

控制台出错:未捕获的TypeError:无法读取未定义的属性“值”

我在客户端的表格活动:

Template.newRecipe.events({
  'submit form'(event) {
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const title = target.title.value;
    const description = target.description.value;
    const ingredients = target.ingredients.value; // line causing above error

    // Insert a task into the collection
    Meteor.call('recipes.insert', title, description, ingredients);
    document.getElementById('insertRecipeForm').reset();
  },
});

我的服务器方法:

Meteor.methods({
  'recipes.insert'(title, description, ingredients) {
    Recipes.insert({
      title,
      description,
      ingredients,
    });
  },
});

我的架构:

Recipes = new Mongo.Collection('recipes');

Ingredient = new SimpleSchema({
  name: {
    type: String
  },
  amount: {
    type: String
  }
});

Recipe = new SimpleSchema({
  title: {
    type: String,
    label: "Title"
  },
  description: {
    type: String,
    label: "Description",
    autoform: {
        rows: 6
    }
  },
  ingredients: {
    type: [Ingredient]
  }
});

Recipes.attachSchema(Recipe);

2 回答

  • 0

    你没有插入一个对象:

    Recipes.insert({
      title,
      description,
      ingredients,
    });
    

    需要是:

    Recipes.insert({
      title: title,
      description: description,
      ingredients: {$push: ingredients},
    });
    
  • 0

    该错误告诉您target.ingredients由于某种原因不存在 . 如果没有看到您的HTML,我们可能无法提供更好的建议 .

相关问题