蒙古族本土的宣传

时间:2015-04-06 15:49:53

标签: node.js mongodb promise bluebird

我正在尝试使用bluebird和mongodb,我收到了错误。

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)

如果您catchthrow e.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)

1 个答案:

答案 0 :(得分: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
})