count.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. const buildCountCommand = require('./common_functions').buildCountCommand;
  3. const OperationBase = require('./operation').OperationBase;
  4. class CountOperation extends OperationBase {
  5. constructor(cursor, applySkipLimit, options) {
  6. super(options);
  7. this.cursor = cursor;
  8. this.applySkipLimit = applySkipLimit;
  9. }
  10. execute(callback) {
  11. const cursor = this.cursor;
  12. const applySkipLimit = this.applySkipLimit;
  13. const options = this.options;
  14. if (applySkipLimit) {
  15. if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip();
  16. if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit();
  17. }
  18. // Ensure we have the right read preference inheritance
  19. if (options.readPreference) {
  20. cursor.setReadPreference(options.readPreference);
  21. }
  22. if (
  23. typeof options.maxTimeMS !== 'number' &&
  24. cursor.cmd &&
  25. typeof cursor.cmd.maxTimeMS === 'number'
  26. ) {
  27. options.maxTimeMS = cursor.cmd.maxTimeMS;
  28. }
  29. let finalOptions = {};
  30. finalOptions.skip = options.skip;
  31. finalOptions.limit = options.limit;
  32. finalOptions.hint = options.hint;
  33. finalOptions.maxTimeMS = options.maxTimeMS;
  34. // Command
  35. finalOptions.collectionName = cursor.namespace.collection;
  36. let command;
  37. try {
  38. command = buildCountCommand(cursor, cursor.cmd.query, finalOptions);
  39. } catch (err) {
  40. return callback(err);
  41. }
  42. // Set cursor server to the same as the topology
  43. cursor.server = cursor.topology.s.coreTopology;
  44. // Execute the command
  45. cursor.topology.command(
  46. cursor.namespace.withCollection('$cmd'),
  47. command,
  48. cursor.options,
  49. (err, result) => {
  50. callback(err, result ? result.result.n : null);
  51. }
  52. );
  53. }
  54. }
  55. module.exports = CountOperation;