2017-01-08 122 views
0

我正在开展在线商店项目。我使用了mongoose来使用Node.js,express.js和MongoDB。我从MongoDB数据库获取产品信息并将它们发送到客户端。就我而言,我可以在客户端获取所有这些数据,但在发送之前,当我将它们打印到服务器端的控制台时,它说未定义。如何打印数据,从Node.js中的mongoDB数据库中检索?

这是产品架构:

var schema = new Schema({ 
    imagePath: { 
     type: String, 
     required: true 
    }, 
    productName: { 
     type: String, 
     required: true 
    }, 
    productPrice: { 
     type: Number, 
     required: true 
    }, 
    productCategory: { 
     type: String, 
     required: true 
    }, 
    productShortInformation: { 
     type: String, 
     required: true 
    }, 
    productFullInformation: { 
     type: String, 
     required: true 
    }, 
    productViews: { 
     type: Number, 
     required: false 
    }, 
    productStock: { 
     type: Number, 
     required: true 
    } 
}); 

这里是我的Node.js代码

router.get('/category/summary', function(req, res, next) { 
    //getting my all products information 
    var products = Product.find(function (err, docs) { 
     if(err) { 
      console.log('Error Happened' + err); 
      return res.redirect('/'); 
     } else { 
      //HERE IS THE PROBLEM 
      //ALL PRODUCT NAME IS SHOWN UNDEFINED 
      //BUT WHEN I SEND THEM TO THE CLIENT, I GET PRODUCT NAME 
      for(var product in docs) { 
       console.log('Name: ' + product.productName); 
      } 

      res.render('shop/categorySummary', { 
       products: docs //sending these information to the client side 
      }); 
     } 
    }); 
}); 

当我尝试打印这些产品name,我得到了一个未定义。但在客户端,我可以打印产品信息。

我需要在将这些数据发送到客户端之前处理这些数据。那么如何在发送之前将这些产品信息打印到服务器端(在控制台中)?

回答

3
for(var product in docs) { 
    console.log('Name: ' + docs[product].productName); 
} 

这应该工作

+1

妈呀,非常感谢你。它正在工作。非常感谢。 –

+0

@BShammNahid在Stack Overflow上,我们表示感谢你[**接受帮助我们的答案](http://stackoverflow.com/help/accepted-answer)。在左边的答案旁边有一个绿色的选中标记,您勾选:) – chridam