0

无法弄清楚我在这里做错了什么。下面是我的代码,它没有将任何内容存储到 foods.ingredients 数组中。其他字段(名称、类别)已正确存储。

架构:

var UserSchema = new mongoose.Schema ({
    username: String,
    password: String,
    email: String,
    foods: [{
      name: String,
      category: String,
      ingredients: [String]
    }], 
    ingredients: [{
      name: String,
      category: String
    }]  
});

HTML 表单:

<form action="http://localhost:3000/api/foods" method="post">
  Name
  <input type="text" name="name" />
  <br />
  Category
  <select name="category">
    <option value="meat">meat</option>
    <option value="pasta">pasta</option>
    <option value="soup">soup</option>
  </select>
  <br />
  Ingredients
  <select multiple name="ingredients[]">
    <option value="beef meat">beef meat</option>
    <option value="potatoes">potatoes</option>
    <option value="onion">onion</option>
  </select>
  <br />
  <input type="submit" name="submit" id="submit" value="Submit" />
</form>

api.js:

var search = { 'username': "tester"};
var update = {
  $addToSet: {
    foods: {
      name: req.body.name, 
      category: req.body.category, 
      ingredients: { $each: req.body.ingredients }
    }
  }
}; 

User.findOneAndUpdate(search, update, function(err, food){
    if(err) {
      console.log(err);
      res.end('There was an error saving food.');
    } else {
      res.end('Food saved successfully!');
    };  
  }); 
4

0 回答 0