Search code examples
node.jsmonk

Getting at all fields in the response to a monk findById call. nodejs/express/monk


Just cannot get my head around this after 10 hours of trying:

if I

users.findById(req.body.user_id,function(e,doc){});

and console.log the doc returned, all looks good:

{ _id: 54dcad6de4b01007caacb0cd,
  username: 'realizertest',
  password: '******************************',
  first_name: 'Realizer',
  second_name: 'Test',
  display_name: 'Realizer Test',
  email: 'system@realizerlabs.com' }

However, when trying to access the included fields, e.g. by:

user = users.findById(req.body.user_id,function(e,doc){});
var user_email = user.email;

I just get undefined. The user object looks like this:

{ col:
   { manager:
      { driver: [Object],
        helper: [Object],
        collections: [Object],
        options: [Object],
        _events: {} },
     driver:
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _connect_args: [Object] },
     helper: { toObjectID: [Function], id: [Ob
     name: 'users',
     col:
      { _construct_args: [],
        _native: [Object],
        _emitter: [Object],
        _state: 2,
        _skin_db: [Object],
        _collection_args: [Object],
        id: [Object],
        emitter: [Object] },
     options: {} },
  type: 'findOne',
  opts: { fields: {}, safe: true },
  domain: null,
  _events:
   { error: [ [Function], [Function] ],
     success: [ [Function], [Function] ] },
  _maxListeners: 10,
  emitted: {},
  ended: false,
  success: [Function],
  error: [Function],
  complete: [Function],
  resolve: [Function],
  fulfill: [Function],
  reject: [Function],
  query: { _id: 54dcad6de4b01007caacb0cd } }

I've also tried user.query.email but get the same result.

The findById obviously doesn't return a JSON object that I can use in this way.

How can I get at these fields?


Solution

  • It's an async call, so you need to use the callback, you can't assign that function to a variable:

    users.findById(req.body.user_id,function(e,doc){
        var user = doc;
        console.log(user); //should see the object now, and access the props
    });