javascript - RethinkDB:​​判断结果集中是否有下一个文档

标签 javascript database node.js rethinkdb

使用 RethinkDB JavaScript 驱动程序,有没有办法确定在“cursor.each”或“cursor.on('data')”事件中是否有另一个文档可用?

通过each

cursor.each(function(err, doc) {
        if (err) throw err;

        // process document here
        // Is there a way to tell if there is another doc coming?

    }, function() {
        // End of data here, no document passed
    })
);

或通过 Event Emitter

cursor.on('data', function(doc) { 
    // handle doc, check if another doc is coming or not
});
cursor.on('end', function() { 
    // no document passed, just indicating end of data
})

最佳答案

有几种方法可以解决这个问题。请记住,这些仅在您当前不在 changefeed 中时才有效。 .

<强>1。使用 cursor.toArray()

您可以先将游标转换为数组,然后仅使用索引来确定游标上是否还有另一行。

r 
  .table('hello')
  .filter({ name: 'jorge' })
  .run(conn)
  .then(function (cursor) {
    return cursor.toArray();
  })
  .then(function (array) {
     array.forEach(function (row, i) {
        if (i === array.length - 1) {
           // There are now more rows after this
        } else {
           // There are more rows
        }
     }); 
  });

正如上面提到的 coffeemug,这种方法不适用于大型数据集,因为将游标转换为数组意味着您必须加载所有数据。

<强>2。使用 cursor.next

一种不太方便但性能更高的方法是使用 cursor.next。这样做的方式是,如果游标中没有更多行,游标上的 .next 方法将抛出错误。

你的代码看起来像这样:

r
  .table('hello')
  .filter({ name: 'jorge' })
  .run(conn)
  .then(function (cursor) {
    var hasNextRow = function (cb, prevRow) {
      cursor.next(function (err, row) {
        if (err) cb(false, prevRow);
        if (row) cb(true, prevRow, row);
      })
    };
    var consoleRow = function (row) {
      hasNextRow(function (hasNextRow, prevRow, row) {
        if (prevRow) {
          if (!hasNextRow) console.log('isLast');
          // This is your row
          console.log(i, prevRow);
        }
        if (hasNextRow) {
          consoleRow(row);
        }
      }, row);
    };
    consoleRow();
  });

基本上,此代码保存对最后一行的引用并继续到下一行。届时,它会知道下一行是否存在,您可以使用 prevRow 变量处理该行的任何行为。

关于javascript - RethinkDB:​​判断结果集中是否有下一个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585123/

相关文章:

database - Sequelize中如何使用findOrCreate

java - 是否需要开始事务才能在数据库中查找对象?

javascript - Codewars "Closest and Smallest"- 与预期输出不匹配

node.js - Sequelize 销毁函数是如何工作的?

javascript - IE6 中的出生日期选择器问题

ios - 为足球教练的行为设计一个核心数据模型

javascript - 将 BN 转换为数字

node.js - NestJS 如何将自定义 Logger 添加到自定义 ExceptionFilter

javascript - Jquery Ajax表单提交: multiple forms - same button-id's

javascript - 仅在响应式 View 中触发 jQuery 函数