0

At my wits end. Can't seem to figure out why this is happening.

Trade.findOne( { ticker } ).then( ( err, doc ) => {
  if ( err ) {
    console.log( 'THERE IS AN ERROR:', '\n', err )
  } else {
    console.log( 'no error' )
    if ( doc ) {
      console.log( 'doc', doc )
    } else {
      console.log( 'no doc' )
    }
  }
} )

When this block of code runs, it goes into the error case and console logs THERE IS AN ERROR and when I log out err, it logs out the correct document that was found. I can't seem to figure out why this is happening. Is there a better error message to be found?

I thought maybe something was conflicting with my Schema but I went line by line through the data and still nothing.

EDIT:

So strange... I changed up the structure of my code to this:

Trade.findOne( { ticker } ).then( doc => {
  if ( doc ) {
    console.log( 'doc', doc )
  } else {
    console.log( 'no doc' )
  }
} ).catch( err => {
  console.log( 'err', err )
} )

This works... Why?

Syn
  • 938
  • 1
  • 10
  • 21

1 Answers1

0

Mongoose's callbacks provide the error as the first argument and result as the second argument.

When using promises, errors are caught in the catch handler as you have above - and the result cascades through then handlers.

Have a look at:

Adam W
  • 317
  • 1
  • 3
  • 15