2015-07-22 25 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); 
}) 

为了在阵列中添加的每个数组元素的数组属性您所创建的文件内。