Sunday, 9 April 2017

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

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?



via SAS

No comments:

Post a Comment