我在NodeJS和MongoDB中構建了一個簡單的配方插入工具,以便了解MEAN堆棧。每個配方都有一個標題,說明和成分數組(可以有多個成分數組),它們都有成分名稱。我試着運行一個簡單的cURL查詢來將測試配方插入到數據庫中,並且出現以下錯誤:Cannot read property 'name' of undefined
,位於以下行:name: req.ingredients.name
。這篇文章有2個問題。第一個是(它也可能回答第二個),當將數據插入數據庫時,以下方法是否正確?其次,拋出這個錯誤的數組插入有什麼問題?由於可能有多個「成分」數組,下面的方法會在執行過程中拋出錯誤嗎?使用NodeJS將多個數組插入MongoDB Post route
路線\ index.js
router.post('/recipes', function(req, res, next) {
var recipe = new Recipe();
recipe.description = req.description;
recipe.title = req.title;
recipe.ingredients = [{
name: req.ingredients.name
}];
recipe.save(function(err, recipe){
if(err){ return next(err); }
res.json(recipe);
});
});
請讓我知道如果我需要提供更多的細節。
編輯:添加額外的細節
C:\>curl --data "description=howdy&title=test&ingredient[name]=apple" http://localhost:3000/recipes
<h1>Cannot read property 'name' of undefined</h1>
<h2></h2>
<pre>TypeError: Cannot read property 'name' of undefined
at C:\app\routes\index.js:33:26
...
這裏需要的細節將包括您通過cURL發佈的數據,實際上命令甚至可以查看cURL語法是否正確。然後,當然取決於看起來像什麼,當你「記錄」變量時,你也可以看到'req.ingredients'看起來是什麼樣子,因爲你可能會有解析器問題與輸入。 –