2015-04-06 28 views
1

我试图使用蓝鸟和mongodb,我得到一个错误。mongodb本地Promiseification

var Promise = require("bluebird") 
var MongoDB = require("mongodb") 
Promise.promisifyAll(MongoDB) 

return MongoDB.connectAsync(process.env.MONGO_URL).then(function(db){ 
    var collection = db.collection('queue') 
    return collection.find().toArray().then(function(docs){ 
    console.log(docs) 
    }) 
}).catch(function(e){ 
    console.log(e.message) 
    throw e 
}) 

我得到这个错误:

Unhandled rejection Error 
    at Object.<anonymous> (/Users/thomas/Desktop/project/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:42:24) 
    at Module._compile (module.js:410:26) 
    at Object.Module._extensions..js (module.js:428:10) 
    at Module.load (module.js:335:32) 
    at Function.Module._load (module.js:290:12) 
    at Module.require (module.js:345:17) 
    at require (module.js:364:17) 
    at Object.<anonymous> (/Users/thomas/Desktop/project/node_modules/mongodb/node_modules/mongodb-core/index.js:2:17) 
    at Module._compile (module.js:410:26) 
    at Object.Module._extensions..js (module.js:428:10) 
    at Module.load (module.js:335:32) 
    at Function.Module._load (module.js:290:12) 
    at Module.require (module.js:345:17) 
    at require (module.js:364:17) 
    at Object.<anonymous> (/Users/thomas/Desktop/project/node_modules/mongodb/index.js:2:12) 
    at Module._compile (module.js:410:26) 

,如果你catchthrowe.message你看到这一点:

Unhandled rejection Error: callback is mandatory 
    at Object.ensureErrorObject (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/util.js:226:20) 
    at Promise._rejectCallback (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:416:22) 
    at Promise._settlePromiseFromHandler (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:460:17) 
    at Promise._settlePromiseAt (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:530:18) 
    at Promise._settlePromises (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/promise.js:646:14) 
    at Async._drainQueue (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/async.js:132:16) 
    at Async._drainQueues (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/async.js:142:10) 
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/thomas/Desktop/project/node_modules/bluebird/js/main/async.js:16:14) 
    at processImmediate [as _immediateCallback] (timers.js:357:17) 

回答

2

不得不使用.toArrayAsync()

var Promise = require("bluebird") 
var MongoDB = require("mongodb") 
Promise.promisifyAll(MongoDB) 

return MongoDB.connectAsync(process.env.MONGO_URL).then(function(db){ 
    var collection = db.collection('queue') 
    return collection.find().toArrayAsync().then(function(docs){ 
    console.log(docs) 
    }) 
}).catch(function(e){ 
    console.log(e.message) 
    throw e 
})