在 nodejs / mongoose / bluebird 中无法得到我对 return 的承诺

Cannot get my promise to return in nodejs / mongoose / bluebird

我正在使用蓝鸟。

我还为模型使用了 bluebird 的 Promisify。

var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose')); 
var Collection = Promise.promisifyAll(require('../models/collection'));
var Vote = Promise.promisifyAll(require('../models/vote'));

在我的整个项目中,它一直运行成功,但由于某种原因,我无法将其获取到 return 此 'save' 方法的集合值。

这是我的模型:

var CollectionSchema = new mongoose.Schema({
  user : {type: mongoose.Schema.ObjectId, ref: 'User', required: true},
  whiskey : {type: mongoose.Schema.ObjectId, ref: 'Whiskey', required: true},
  favorite: {type: Boolean, default: false},
  timestamp: { type : Date, default: Date.now }
});

    CollectionSchema.statics.createCollection = function(o) {
      console.log('hit model')
        return Collection
        .findAsync(o)
        .then(function(existing) {
          console.log('existing collection ', existing)
          if (existing.length) {
            return{
              message: 'already collected'
            }
          } else {
            console.log('no existing collections found')
           return Collection
            .saveAsync(o)
            .then(function(collection) {
              console.log('new collection / does not console.log ', collection)
              return {
                collection: collection
              };
            });
          }
        })
      };

这是控制器,其中调用了 collectionCreate 方法并期待来自 promise 的响应 'data'。但是,saveAsync mongoose 方法似乎没有调用或 return :

exports.create = function(req, res){
  console.log('init')
  console.log('init body ', req.body)
  Collection.createCollectionAsync({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){
    console.log('collection promise ', data)
    res.send(data);
  })
};

我真的可以用第二只眼睛指出我哪里做错了。

您不应该使用已经 return 承诺的 …Async 承诺版本的函数。这只会导致 Bluebird 传递一个从未被调用的额外回调。

Collection.createCollection({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){
    res.send(data);
}, function(err) {
    …
})