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
可能有人請指導我實現這個,讓我知道錯誤是什麼?
你不能用'JSON.parse'的對象,它必須是JSON字符串 –