Unable to access the meta data inside a data which is in JSON format using nodejs

时间:2017-04-10 03:17:08

标签: node.js

New to nodejs. This might be a very basic question. I have fetched data from mongoDB which is in JSON format. Please find the sample data below.

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

I am trying to access and get the value of the meta data called "name" inside a JSON formatted data inside "doc" using nodejs. But unable to do so. Please find the code below.

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

When I run the above code, I am getting the following error.

SyntaxError: Unexpected token o in JSON at position 1

I even tried the below code but no luck. Ended up getting the same error.

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

When I tried this, I got the following error.

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

Could somebody please guide me in implementing this and let me know where the mistake is?

1 个答案:

答案 0 :(得分: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);
         }
      })        
   }    
});

这对我有用,我在当地尝试......