【问题标题】:TypeError: Cannot read property 'length' of undefined node.jsTypeError:无法读取未定义 node.js 的属性“长度”
【发布时间】:2017-11-29 04:11:10
【问题描述】:

我正在尝试将多个数据插入 mongoDB。数据来自另一个 JSON 格式的 Web 服务。我收集这些数据并存储在我的数据库中。但是,当我尝试遍历收集的项目时,我得到了问题中提到的类型错误。

// Add purchase details to DB (Userid, Productid, Category)
router.post('/addpurchased', function(req, res){
    // Connect to the server
    MongoClient.connect(url, function(err, db){
      if (err) {
        console.log('Unable to connect to the Server:', err);
      } else {
        console.log('Connected to Server',url);


    // Get the documents collection
    var collection = db.collection('purchased');

    var arrProducts = req.body.products;
    var userProducts = [];

    for(var i = 0; i < arrProducts.length; i++){
      // Get the purchased details passed from the form
      var user = {userid: arrProducts[i].userid, productid: arrProducts[i].productid, category: arrProducts[i].category,
         purchasetime: new Date()};

      userProducts.push(user);
    }

    // Insert the purchase data into the database
    collection.insert(userProducts, function (err, result){
      if (err) {
        console.log(err);
      } else {
        res.send("Purchase Details Added")
      }
    });
  }
});

});

请让我知道我在这里缺少什么。

我正在通过邮递员传递 JSOM 数据,如下所示,

并得到如下错误信息。

【问题讨论】:

  • arrProducts的内容是什么?在下一行设置一个断点,并在调试器中检查 arrProducts 包含的内容。你会看到它是未定义的。所以很可能在products的请求正文中没有提交任何数据
  • 显然您的req.body.productsundefined,这意味着您没有将products 正确传递给您的API 方法
  • 这个 arrProducts[] 的输出是什么?
  • arrProducts 没有任何内容。我已经更新了问题,请让我知道我做错了什么。

标签: json node.js mongodb express


【解决方案1】:

正如 cmets 中的其他人所提到的,您的 req.body.products 为 null。这将解决您的错误,但您需要弄清楚为什么您没有获得产品。

 var arrProducts = [];
  if(req && req.body && req.body.products){
   var arrProducts = req.body.products;
  }

  for(var i = 0; i < arrProducts.length; i++){
  // Get the purchased details passed from the form
  var user = {userid: arrProducts[i].userid, productid: arrProducts[i].productid, category: arrProducts[i].category,
     purchasetime: new Date()};

  userProducts.push(user);
}

你可以通过打印出正文的内容来调试或

console.log(req.body);

【讨论】:

  • 不是null,而是undefined
  • @camccar ,是的,它是未定义的,我从邮递员那里传递数据,但是有一个问题三,请看看是否可以纠正。
【解决方案2】:

邮递员的 JSON 格式错误。 使用 JSON 格式的引号,因为请求需要它是一个字符串。

如果您将在 Javascript XHR 请求中使用它,您需要在向服务器发送请求之前使用 JSON.stringify(object)。

{ 
"products": [
       {
        "productid" : "first",
        "userid" : "1",
        "category": "edu"
       },
       {
        "productid" : "second",
        "userid" : "2",
        "category": "edu"
       }
]
}

【讨论】:

    【解决方案3】:

    感谢您的线索。我没有正确传递 JSON 数据。现在它工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2021-12-05
      • 2020-07-20
      • 2020-03-07
      相关资源
      最近更新 更多