简体   繁体   中英

TypeError: Cannot read property 'length' of undefined node.js

I am trying to insert multiple data into mongoDB. Data comes from another web service in JSON format. I collect that data and store in my DB. But, when I am trying to iterate over collected items, I get Type Error as mentioned in Question.

// 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")
      }
    });
  }
});

});

Please let me know what I am missing here.

I am passing JSOM data from postman as below, 在此处输入图片说明

and get error message as below. 在此处输入图片说明

As others mentioned in comments, your req.body.products is comming in null. This will fix your error, but then you need to figure out why you are not getting products.

 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);
}

You can do that by printing out the contents of body to debug or

console.log(req.body);

You have wrong JSON format in postman. Use inverted commas in JSON format as request requires it to be as a string.

If you will use this from Javascript XHR request you need to use JSON.stringify(object) before sending request to server.

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

Thanks for the leads. I was not passing JSON data properly. Now it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM