我正在使用 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'));
在我的整个项目中,它一直运行成功,但由于某种原因,我无法让它在这个“保存”方法上返回集合值。
这是我的模型:
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
};
});
}
})
};
这里是 Controller ,其中调用了 collectionCreate 方法并期望来自 Promise 的响应“数据”。但是,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
promise 版本。这只会导致 Bluebird 传递一个从未被调用的额外回调。
Collection.createCollection({user: req.user._id, whiskey: req.body.whiskey}).then(function(data){
res.send(data);
}, function(err) {
…
})
关于javascript - 无法得到我在 nodejs/mongoose/bluebird 中返回的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493262/