简体   繁体   English

Mongoose findOne将文档作为错误返回?

[英]Mongoose findOne is returning the doc as the error?

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. 当这段代码运行时,它进入错误情况和控制台日志,这THERE IS AN ERROR ,当我注销err ,它会注销找到的正确文件。 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? 这有效...为什么?

Mongoose's callbacks provide the error as the first argument and result as the second argument. Mongoose的回调提供错误作为第一个参数,结果作为第二个参数。

When using promises, errors are caught in the catch handler as you have above - and the result cascades through then handlers. 使用promises时,错误会像上面一样在catch处理程序中捕获 - 并且结果通过then处理程序进行级联。

Have a look at: 看一下:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM