cursor_ops.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. 'use strict';
  2. const buildCountCommand = require('./collection_ops').buildCountCommand;
  3. const handleCallback = require('../utils').handleCallback;
  4. const MongoError = require('../core').MongoError;
  5. const push = Array.prototype.push;
  6. const CursorState = require('../core/cursor').CursorState;
  7. /**
  8. * Get the count of documents for this cursor.
  9. *
  10. * @method
  11. * @param {Cursor} cursor The Cursor instance on which to count.
  12. * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options.
  13. * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options.
  14. * @param {Cursor~countResultCallback} [callback] The result callback.
  15. */
  16. function count(cursor, applySkipLimit, opts, callback) {
  17. if (applySkipLimit) {
  18. if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip();
  19. if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit();
  20. }
  21. // Ensure we have the right read preference inheritance
  22. if (opts.readPreference) {
  23. cursor.setReadPreference(opts.readPreference);
  24. }
  25. if (
  26. typeof opts.maxTimeMS !== 'number' &&
  27. cursor.cmd &&
  28. typeof cursor.cmd.maxTimeMS === 'number'
  29. ) {
  30. opts.maxTimeMS = cursor.cmd.maxTimeMS;
  31. }
  32. let options = {};
  33. options.skip = opts.skip;
  34. options.limit = opts.limit;
  35. options.hint = opts.hint;
  36. options.maxTimeMS = opts.maxTimeMS;
  37. // Command
  38. options.collectionName = cursor.namespace.collection;
  39. let command;
  40. try {
  41. command = buildCountCommand(cursor, cursor.cmd.query, options);
  42. } catch (err) {
  43. return callback(err);
  44. }
  45. // Set cursor server to the same as the topology
  46. cursor.server = cursor.topology.s.coreTopology;
  47. // Execute the command
  48. cursor.topology.command(
  49. cursor.namespace.withCollection('$cmd'),
  50. command,
  51. cursor.options,
  52. (err, result) => {
  53. callback(err, result ? result.result.n : null);
  54. }
  55. );
  56. }
  57. /**
  58. * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information.
  59. *
  60. * @method
  61. * @deprecated
  62. * @param {Cursor} cursor The Cursor instance on which to run.
  63. * @param {Cursor~resultCallback} callback The result callback.
  64. */
  65. function each(cursor, callback) {
  66. if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true });
  67. if (cursor.isNotified()) return;
  68. if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) {
  69. return handleCallback(
  70. callback,
  71. MongoError.create({ message: 'Cursor is closed', driver: true })
  72. );
  73. }
  74. if (cursor.s.state === CursorState.INIT) {
  75. cursor.s.state = CursorState.OPEN;
  76. }
  77. // Define function to avoid global scope escape
  78. let fn = null;
  79. // Trampoline all the entries
  80. if (cursor.bufferedCount() > 0) {
  81. while ((fn = loop(cursor, callback))) fn(cursor, callback);
  82. each(cursor, callback);
  83. } else {
  84. cursor.next((err, item) => {
  85. if (err) return handleCallback(callback, err);
  86. if (item == null) {
  87. return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null));
  88. }
  89. if (handleCallback(callback, null, item) === false) return;
  90. each(cursor, callback);
  91. });
  92. }
  93. }
  94. // Trampoline emptying the number of retrieved items
  95. // without incurring a nextTick operation
  96. function loop(cursor, callback) {
  97. // No more items we are done
  98. if (cursor.bufferedCount() === 0) return;
  99. // Get the next document
  100. cursor._next(callback);
  101. // Loop
  102. return loop;
  103. }
  104. /**
  105. * Returns an array of documents. See Cursor.prototype.toArray for more information.
  106. *
  107. * @method
  108. * @param {Cursor} cursor The Cursor instance from which to get the next document.
  109. * @param {Cursor~toArrayResultCallback} [callback] The result callback.
  110. */
  111. function toArray(cursor, callback) {
  112. const items = [];
  113. // Reset cursor
  114. cursor.rewind();
  115. cursor.s.state = CursorState.INIT;
  116. // Fetch all the documents
  117. const fetchDocs = () => {
  118. cursor._next((err, doc) => {
  119. if (err) {
  120. return cursor._endSession
  121. ? cursor._endSession(() => handleCallback(callback, err))
  122. : handleCallback(callback, err);
  123. }
  124. if (doc == null) {
  125. return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items));
  126. }
  127. // Add doc to items
  128. items.push(doc);
  129. // Get all buffered objects
  130. if (cursor.bufferedCount() > 0) {
  131. let docs = cursor.readBufferedDocuments(cursor.bufferedCount());
  132. // Transform the doc if transform method added
  133. if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') {
  134. docs = docs.map(cursor.s.transforms.doc);
  135. }
  136. push.apply(items, docs);
  137. }
  138. // Attempt a fetch
  139. fetchDocs();
  140. });
  141. };
  142. fetchDocs();
  143. }
  144. module.exports = { count, each, toArray };