了解Node / Mongo中的查找
我正在学习节点。 考虑这个代码(基于官方的MongoDB Node.js驱动程序)
// Retrieve all the documents in the collection collection.find().toArray(function(err, documents) { assert.equal(1, documents.length); assert.deepEqual([1, 2, 3], documents[0].b); db.close(); });
我有两个问题:
- 是
find
同步还是asynchronous? -
如果它是asynchronous的,那么
.toArray
函数调用会让我感到困惑,因为通常情况下我会期望沿着这个方向.toArray
collection.find(function(err, results){});
具体来说,我感兴趣的是什么机制允许你在asynchronous函数的结果上调用.toArray
? 因为我得到它的asynchronous函数很less返回一些东西(我认为除了promises),而是调用传递给它们的callback函数。 有人可以用find和.toArray
澄清这种情况吗?
例如在这个问题的被接受的答案: 如何获得MongoDB的collection.find()callback ,你可以看到作者调用find
我设想的方式,并在callback函数接收cursor
。 这对我来说很好,这就是我期望的工作方式。 但链接asynchronous调用find
结果(如果是asynchronous?), toArray
有点困惑我。
我的猜测是find
返回一个句柄类的东西,此时数据还没有从数据库加载,只有当你调用toArray
的实际数据到达。 我对吗?
我承认你,这个案子有点怪异。 这里是mongodb-native的v2.2。
首先, find
有两种不同的用法 。 你可以给一个callback函数或不。 但是无论如何 ,它会同步返回一个对象。 更确切地说,它是一个游标 。 我们可以期待一个asynchronous机制,当传递一个callback,但不在这里。
collection.find({ }, function (err, cursor) { assert(!err); }); console.log('This happens after collection.find({ }, callback)');
要么
const cursor = collection.find({}); console.log('Also happening after');
另一方面, toArray
是一个asynchronous函数,也有两种不同的用法。 这一次,返回的对象根据参数的不同而不同。
相当于:
cursor.toArray(function (err, documents) { assert.equal(1, documents.length); });
和
cursor.toArray() .then(documents => { assert.equal(1, documents.length); });
在第一次调用中, toArray
返回undefined
而第二次返回Promise
。