最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

理解NodeMongo中的find

IT培训 admin 7浏览 0评论

理解Node / Mongo中的find

我正在努力学习节点。考虑一下这段代码(基于官方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?因为我得到的异步函数很少返回一些东西(我认为除了promises),而是调用传递给它们的回调。有人能用find和.toArray澄清这种情况吗?


例如,在这个问题的接受答案:How to get a callback on MongoDB collection.find(),你可以看到作者按照我设想的方式调用find,并在回调函数中收到cursor。这对我很好,这就是我期望它的工作方式。但链接异步调用find的结果(如果它是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

理解Node / Mongo中的find

我正在努力学习节点。考虑一下这段代码(基于官方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?因为我得到的异步函数很少返回一些东西(我认为除了promises),而是调用传递给它们的回调。有人能用find和.toArray澄清这种情况吗?


例如,在这个问题的接受答案:How to get a callback on MongoDB collection.find(),你可以看到作者按照我设想的方式调用find,并在回调函数中收到cursor。这对我很好,这就是我期望它的工作方式。但链接异步调用find的结果(如果它是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

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论