Promise 问题:使用 Q.nfcall() 调用 mongoose.findOne()

Promise issue: using Q.nfcall() to call mongoose.findOne()

我有以下代码,其中 mongoosefindOne 方法使用 Q.promise 包装:

// _getById should be returning a Promise
var _getById = function(id) {
  return Q.Promise(function(resolve, reject) {

    ApplicationModel.findOne({
      _id: id,
      'metadata.isDisabled': false
    },
    '-metadata',
    function(err, application) {
      if (err) {
        return reject(err);
      }

      if (!application) {
        return reject(new CustomError('Not found', 404));
      }

      resolve(application);
    });

  });
}

我正在尝试使用 Q.nfcall 方法重构该代码,这是我目前所拥有的:

var _getById = function(id) {
  var searchOptions = {
    _id: id,
    'metadata.isDisabled': false
  };

  return Q.nfcall(ApplicationModel.findOne, searchOptions, '-metadata')
    .then(function(application) {
      if (!application) {
        throw new CustomError('Not found', 404);
      }
      return application;
    });
}

但它不起作用,我在屏幕上收到以下[​​=30=]错误:

info: TypeError: Cannot read property 'discriminatorMapping' of undefined at findOne [...]

似乎 findOne 方法未使用 Q.nfcall 正确调用,我正在关注 Q's API Reference for nfcall function,但我看不出原因。

Mongoose 已经承诺。因此,您的代码可以简单地是:

var _getById = function(id) {
  var searchOptions = {
    _id: id,
    'metadata.isDisabled': false
  };

  return ApplicationModel.findOne(searchOptions, '-metadata')
    .then(function(application) {
      if (!application) {
        throw new CustomError('Not found', 404);
      }
      return application;
    });
}