无法在nodejs/mongoose/bluebird中获得返回的承诺

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

本文关键字:返回 承诺 bluebird nodejs mongoose      更新时间:2023-09-26

我正在使用bluebird。

我还使用了蓝鸟的Promiseify作为模型。

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

在我的整个项目中,它一直在成功地工作,但由于某种原因,我无法让它返回这个"保存"方法的集合值。

这是我的型号:

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方法似乎不会调用或返回:

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);
  })
};

我真的可以用第二双眼睛来指出我做错了什么。

您不应该使用已经返回promise的函数的…Async promised版本。这只会导致Bluebird传入一个从未调用过的额外回调。

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