node accessing object properties

42 views
Skip to first unread message

Joachim Rodrigues

unread,
Oct 14, 2014, 10:58:01 AM10/14/14
to nod...@googlegroups.com
Hi 
i'm a beginer in node and i'm struggled with a behavior.

In my route


  var list_subscriber_projects ;
  var list_subscriber_projects_request  = Subscriber.find({ user_email: req.params.user_email });
  var list_subscriber_projects_promise = list_subscriber_projects_request.exec( );
  list_subscriber_projects_promise.addBack(function ( err, list_subscriber_projects_result ){
      if( err ) return next( err );
      console.log("1 - test ------> " + list_subscriber_projects_result);
      console.log("2 - test------> " + list_subscriber_projects_result.subscriptions);
      list_subscriber_projects = list_subscriber_projects_result;
  });
  console.log("3 - test------> " + list_subscriber_projects);



And in my console i'm getting : 

3 - test------> undefined
1 - test ------> { __v: 1,
  _id: 543beeeefc966c642e5fa2e2,
  user_email: 'use...@sdsd.com',
  subscriptions:
   [ { project_name: 'ffffff',
       _id: 543d21761ad0e1cc18c639af } ] }
2 - test------> undefined


So my question is why log test 1 tells me that the object has subscriptions property and when trying to access these  property log test 2 tells that it is undifined
and then when i copy in an other object i have also undifined ?

Thanks 

Jimb Esser

unread,
Oct 15, 2014, 2:33:02 PM10/15/14
to nod...@googlegroups.com
Test 1 is concatenating a string with an object, usually that would convert the object into the string "[object Object]", not give you a nice result like that, so that object must have overridden it's .toString method to show what you're seeing there.  It's returning whatever it wants, does not necessarily have any reflection on what members of that object exist.  And, as you can see from test 2, that member doesn't actually exist.  If instead you log require('util').inspect(that_object), you'll see actual members of the object.  However, the object probably has some API you should call to get subscribers.

As for Test 3, that runs  synchronously, and as you can see from your logs, this is before your callback that includes Test 1 and 2 have been executed.  Test 3 is running right after the exec() has been dispatched, but before the results have come back, so your value is still undefined.  You may want to read up on asynchronous programming in Javascript if these concepts are unfamiliar to you.
Reply all
Reply to author
Forward
0 new messages