node.js - Can only access top level values in MongoDB response


Keywords:node.js 


Question: 

I am using node to access data in MongoDB shown below, the document in my collection is this:

{
    "key_a" : "val_a",
    "key_b" : [ 
        {
            "sub_b_keya" : "jenkins",
            "sub_b_keyb" : "foo"
        }, 
        {
            "sub_b_keya" : "kubernetes/0",
            "sub_b_keyb" : "bar"
        }
    ]
    "key_c": 0
}

When i console log the response it prints everything just fine, but when i try to access the value at key, "sub_b_keya" it is undefined in the code below! Does the .toArray() not load sub documents into RAM, and only the top structure of the document or something?!

MongoClient.connect(uri, (err, client) => {
    if (err){
        console.log(err);
    }
    database = client.db(databaseName)
    getAwsDisplayInstances(function(data){
        if(data.length > 0){
            db_response = data;
            foo = db_response['key_b'][0]['sub_b_keya'];
            console.log(foo); //This prints undefined
        }
    })
})

function getAwsDisplayInstances(callback){
    var query = { key_a: "val_a" };
    database.collection(awsCollectionName).find(query).toArray(function(err, result){
        if (err){
            throw err;
        }
        callback(result);
    })
}

2 Answers: 

mongoDB find query returns an array of documents what you're trying is to access the returned data as if it is an object

Try

database.collection(awsCollectionName).findOne(query)

If you need to get only one object

Else loop through the data

if(data.length > 0){
  for(var db_response of data){
            foo = db_response['key_b'][0]['sub_b_keya'];
            console.log(foo); //This won't print undefined
   }
}
 

If you're using find you will have to iterate the data also, below code will work fine with findOne query.

 getAwsDisplayInstances(function (data) {
      if (data && data.hasOwnProperty('key_b')) {
        for (let i = 0; i < data['key_b'].length; i++) {
          const db_response = data['key_b'][i];
          foo = db_response['sub_b_keya'];
          console.log(foo); //This will print your required output
        }
      }
    });