2017-04-10 54 views
0

nodejs的新手。這可能是一個非常基本的問題。 我已經從JSON格式的mongoDB中獲取數據。 請在下面找到示例數據。無法使用nodejs訪問JSON格式的數據中的元數據

{ 
    index: 0, 
    name: 'Matt Sweeney', 
    color: '#FFFFFF', 
    display: true, 
    Age: '24’, 
    Weight: '60’ 
} 

我試圖訪問並獲得所謂的「名」 JSON格式的數據裏的「doc」使用裏面的NodeJS元數據的價值。但無法這樣做。 請找到下面的代碼。

var MongoClient = require('mongodb').MongoClient; 
    var url = 'mongodb://localhost/TestDB'; 
    MongoClient.connect(url,function (err,db) { 
     if(err) throw err 
     console.log("connected for select"); 

     var cursor = db.collection('TestCollection').find(); 
     cursor.each(function(err,doc){ 
      console.log(doc); 
      var Athname = doc; 

      console.log(JSON.parse(Athname).name); 
     }); 

當我運行上面的代碼時,出現以下錯誤。

SyntaxError: Unexpected token o in JSON at position 1

我甚至嘗試了下面的代碼,但沒有運氣。結束得到相同的錯誤。

var MongoClient = require('mongodb').MongoClient; 
     var url = 'mongodb://localhost/TestDB'; 
     MongoClient.connect(url,function (err,db) { 
      if(err) throw err 
      console.log("connected for select"); 

      var cursor = db.collection('TestCollection').find(); 
      cursor.each(function(err,doc){ 
       console.log(doc); 
       var Athname = JSON.parse(doc).name; 

       console.log(Athname); 
      }); 

當我嘗試這個時,我得到以下錯誤。

var MongoClient = require('mongodb').MongoClient; 
     var url = 'mongodb://localhost/TestDB'; 
     MongoClient.connect(url,function (err,db) { 
      if(err) throw err 
      console.log("connected for select"); 

      var cursor = db.collection('TestCollection').find(); 
      cursor.each(function(err,doc){ 
       console.log(doc); 
       var Athname = doc.name; 

       console.log(Athname); 
      }); 

TypeError: Cannot read property 'name' of null

可能有人請指導我實現這個,讓我知道錯誤是什麼?

+0

你不能用'JSON.parse'的對象,它必須是JSON字符串 –

回答

0

如果你想達到同樣的效果,那麼你也可以使用.toArray函數來得到一個數組數組,你可以爲它或者東西在裏面循環。

var MongoClient = require('mongodb').MongoClient; 

var url = 'mongodb://localhost:27017/TestDB'; 

MongoClient.connect(url,function (err,db) { 
    if(err) { 
     throw err    
    } else { 
     var testCollection = db.collection('testCollection'); 
     testCollection.find({}).toArray(function(err, data){ 
     if(err) { 
      console.log(err); 
     } else { 
      console.log(data); 
     } 
     })   
    }  
}); 

這是爲我工作,我在當地試圖...

+0

感謝ü您的回覆Prasanth。我試圖做到這一點,但沒有運氣。它不起作用。有沒有其他的選擇 – SAS