2015-07-22 24 views
0

我在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 &#39;name&#39; of undefined</h1> 
<h2></h2> 
<pre>TypeError: Cannot read property &#39;name&#39; of undefined 
    at C:\app\routes\index.js:33:26 
    ... 
+0

這裏需要的細節將包括您通過cURL發佈的數據,實際上命令甚至可以查看cURL語法是否正確。然後,當然取決於看起來像什麼,當你「記錄」變量時,你也可以看到'req.ingredients'看起來是什麼樣子,因爲你可能會有解析器問題與輸入。 –

回答

0

我認爲這是一個「錯字」,在那裏有應該被稱爲「成分」,而不是「成分」爲你那裏。但是你的符號也不是「嚴格」的陣列,因爲你應該這樣做:

cURL的defauly格式是x-www-formencoded,所以這就是它期望的數據。所以,如果我做使用jQuery .param()快速測試,我得到:

$.param({ "ingredients": [ { "name": "apple" }, { "name": "orange" }] }) 

這是出來:

"ingredients%5B0%5D%5Bname%5D=apple&ingredients%5B1%5D%5Bname%5D=orange" 

或者從已編碼格式轉換(從here幫助),然後你會得到:

"ingredients[0][name]=apple&ingredients[1][name]=orange" 

它代表了與我用作輸入的數據結構相同的東西。

只要你有正確的解析器來解碼編碼的URL,那麼是否已經有一個req.ingredients應該是一個「數組」。請參閱body-parser以瞭解正確的設置。

然後你只需要做:

req.ingredients.forEach(function(ingredient) { 
    recipe.ingredients.push(ingredient); 
}) 

爲了在陣列中添加的每個數組元素的數組屬性您所創建的文件內。