node.js 中关于回调和 .toArray 的一些混淆

Some confusion about callbacks and .toArray in node.js

我在一个应用程序上做了一些工作,然后被告知要回去找出测试失败的原因。在这样做的过程中,我遇到了一些让我感到困惑的代码。

这段代码应该用序列号在数据库中找到一个设备:

exports.findBySerial = function (serial, cb) {
  db.devices.find({serial: serial}).toArray((err, count, myDevices) => {
    if (err) {
      return cb(err)
    }
    if (count.length === 0) {
      return cb(null, null)
    } else if (count.length === 1) {
      return cb(null, myDevices[0])
    } else {
      console.error('More than one device with serial no: ' + serial)
      return cb(err)
    }
  })
}

第一行使用来自同一设备存储库的不同调用,.find:

exports.find = function (search, sort, pagination, cb) {
  const curFind = db.devices.find(search).sort(sort)
  curFind.count((err, count) => {
    if (err) console.log(err)
    if (pagination) {
      curFind.skip((pagination.cp - 1) * pagination.pp).limit(pagination.pp).toArray((err, devices) => {
        if (err) {
          return cb(err)
        } else {
          return cb(null, count, devices)
        }
      })
    } else {
      curFind.toArray((err, devices) => {
        if (err) {
          return cb(err)
        } else {
          return cb(null, count, devices)
        }
      })
    }
  })
}

让我感到困惑的是 .find 应该有一个回调,它会接受 null、count 和 myDevices。但是在 .findBySerial 中, .find. 调用没有回调。相反,.toArray() 有一个回调,但它返回了奇怪的东西。例如,无论我做什么,count 都作为一个对象返回,其唯一的 属性 是长度,而 myDevices 一直以未定义的形式返回。但是 count 应该是一个数字,而 myDevices 应该是一个设备数组。

起初我认为我的问题可能是 .find 的结果已经在 .find 中通过了 .toArray() 但文档说调用 .toArray()在数组上就像使用 slice() 一样,这意味着没有参数你将得到该数组的精确副本。所以既然这不是问题,我开始认为它与 .findBySerial.

.find 调用中缺少的回调有关

我在这里很困惑。谁能帮我?问题是我在 .find 中缺少回调并且 .toArray() 中的回调是多余的,还是其他原因?

谢谢。

What confuses me is that the .find is supposed to have a callback

.find returns 游标,根据 documentation 应该进行回调。调用 .toArray 会导致访问游标并将结果作为文档数组获取。

现在,.toArray (docs) 接受回调,其中第一个参数是 error,第二个参数是 data(您的设备列表).因此,在 .findBySerial 中,您所指的 count 实际上是一个设备数组(当然,如果没有错误的话)。而 countlength 的原因是因为它是一个数组。