cursor.toArray()返回一个promise而不是array

目前使用节点4.3.2和mongo 2.6。 我正试图获得一个完整的集合(目前在集合中的三个文档)。 当我使用这段代码时遇到了一个问题。

function checkUpdateTime(last_updated){ var collection = db.collection(last_updated); collection.insert({a:1}); updateTimes = collection.find({a:1}).toArray(); } var updateTimes = []; checkUpdateTime('last_updated'); console.log(updateTimes); 

当这个代码是tun updateTimes是一个承诺,而不是我希望的数组。 目标是编辑数组,然后将其插回到集合中。插入语句有效,但是文档的检索根本无法按我期望的方式操作。 我已经尝试了这个代码的不less版本,但没有骰子。

我想这归结于我想知道为什么一个承诺被退回?

MongoDB驱动程序提供了两个处理asynchronous操作的选项:

  • 通过调用者传递的callback
  • 通过返回一个承诺给调用者

当你不通过callback,就像你的情况,它会返回一个承诺。

所以你需要在这里做出select。 不过,你不能select的一个select是“让这段代码同步运行”

我更喜欢承诺:

 function checkUpdateTime(last_updated){ var collection = db.collection(last_updated); return collection.insert({ a : 1 }) // also async .then(function() { return collection.find({ a : 1 }).toArray(); }); } checkUpdateTime('last_updated').then(function(updateTimes) { console.log(updateTimes); }); 

你总是可以多Promise.coroutine ,并使用类似Promise.coroutine东西,这会使你的代码看起来更加同步(即使它不是):

 const Promise = require('bluebird'); const MongoClient = require('mongodb').MongoClient; let checkUpdateTime = Promise.coroutine(function* (db, last_updated){ let collection = db.collection(last_updated); yield collection.insert({ a : 1 }); return yield collection.find({ a : 1 }).toArray(); }); Promise.coroutine(function *() { let db = yield MongoClient.connect('mongodb://localhost/test'); let updateTimes = yield checkUpdateTime(db, 'foobar'); console.log(updateTimes); })(); 

或者async/await ,使用Babel :

 const MongoClient = require('mongodb').MongoClient; async function checkUpdateTime(db, last_updated) { let collection = db.collection(last_updated); await collection.insert({ a : 1 }); return await collection.find({ a : 1 }).toArray(); } (async function() { let db = await MongoClient.connect('mongodb://localhost/test'); let updateTimes = await checkUpdateTime(db, 'foobar'); console.log(updateTimes); })();