我正在尝试学习 Node 。 考虑这段代码(基于官方 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
是同步的还是异步的?如果它是异步的,那么 .toArray
函数调用会让我感到困惑,因为通常我会期望类似于
collection.find(function(err, results){});
我特别感兴趣什么机制允许你在异步函数的结果上调用.toArray
?因为我得到的异步函数很少返回一些东西(我认为除了 promise ),而是调用传递给它们的回调。有人可以用 find 和 .toArray
澄清这种情况吗?
例如在这个问题的接受答案中:How to get a callback on MongoDB collection.find() ,你可以看到作者按照我想象的方式调用find
,并在回调函数中接收到cursor
。这对我来说很好,这就是我期望它的工作方式。
但是异步调用find
的chaining结果(如果是asynch呢?),用toArray
让我有点迷惑。
我的猜测是 find
返回一个句柄之类的东西,此时数据还没有从 DB 中加载,只有当你调用 toArray
时实际数据到达.我说的对吗?
最佳答案
我承认,这个案子有点奇怪。这是mongodb-native的v2.2。
首先,find
有two different usages .您可以提供或不提供回调函数。但在任何情况中,它同步返回一个对象。更准确地说是 cursor .
我们可以在传递回调时期望异步机制,但这里不是。
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
是一个异步函数,也有两种不同的用法。这一次,返回的对象因参数而异。
等价:
cursor.toArray(function (err, documents) {
assert.equal(1, documents.length);
});
与
cursor.toArray()
.then(documents => {
assert.equal(1, documents.length);
});
在第一次调用中,toArray
返回 undefined
,而在第二次调用中,它返回 Promise
。
https://stackoverflow.com/questions/42305440/
相关文章:
node.js - NodeJS 崩溃 : Mongoose findById() does NOT
mongodb - 在 mongodb 中编辑子文档 N-N 关系
mongodb - 如何将 MongoDB 存档文件转换为 JSON 格式?
node.js - 从nodejs插入日期值到mongodb
mongodb - 选择 2 个字段并返回具有不同值的排序数组
node.js - 防止 Mongoose 模式中数组中的重复条目
php - 在 Ubuntu 14 上将 PHP Mongo 扩展更新到 1.5
mongodb - 如何在大型mongodb集合中高效查询数据?