UnwindDocumentSource.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. "use strict";
  2. var async = require('async'),
  3. DocumentSource = require('./DocumentSource'),
  4. Expression = require('../expressions/Expression'),
  5. FieldPath = require('../FieldPath'),
  6. Value = require('../Value'),
  7. Document = require('../Document');
  8. /**
  9. * A document source unwinder
  10. * @class UnwindDocumentSource
  11. * @namespace mungedb-aggregate.pipeline.documentSources
  12. * @module mungedb-aggregate
  13. * @constructor
  14. * @param [ctx] {ExpressionContext}
  15. **/
  16. var UnwindDocumentSource = module.exports = function UnwindDocumentSource(ctx){
  17. if (arguments.length > 1) {
  18. throw new Error('Up to one argument expected.');
  19. }
  20. base.call(this, ctx);
  21. this._unwindPath = null; // Configuration state.
  22. this._unwinder = null; // Iteration state.
  23. }, klass = UnwindDocumentSource, base = require('./DocumentSource'), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  24. klass.unwindName = '$unwind';
  25. klass.Unwinder = (function() {
  26. /**
  27. * Construct a new Unwinder instance. Used as a parent class for UnwindDocumentSource.
  28. *
  29. * @param unwindPath
  30. * @constructor
  31. */
  32. var klass = function Unwinder(unwindPath) {
  33. this._unwindPath = new FieldPath(unwindPath);
  34. this._inputArray = undefined;
  35. this._document = undefined;
  36. this._index = undefined;
  37. }, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor: {value: klass}});
  38. proto.resetDocument = function resetDocument(document) {
  39. if (!document) throw new Error('Document is required!');
  40. this._inputArray = [];
  41. this._document = document;
  42. this._index = 0;
  43. var pathValue = Document.getNestedField(this._document, this._unwindPath);
  44. if (!pathValue || pathValue.length === 0) {
  45. return;
  46. }
  47. if (!(pathValue instanceof Array)) {
  48. throw new Error(UnwindDocumentSource.unwindName + ': value at end of field path must be an array; code 15978');
  49. }
  50. this._inputArray = pathValue;
  51. };
  52. /**
  53. * getNext
  54. *
  55. * This is just wrapping the old functions because they are somewhat different
  56. * than the original mongo implementation, but should get updated to follow the current API.
  57. **/
  58. proto.getNext = function getNext() {
  59. if (this._inputArray === undefined || this._index === this._inputArray.length) {
  60. return null;
  61. }
  62. this._document = Document.cloneDeep(this._document);
  63. Document.setNestedField(this._document, this._unwindPath, this._inputArray[this._index++]);
  64. return this._document;
  65. };
  66. return klass;
  67. })();
  68. /**
  69. * Get the document source name.
  70. *
  71. * @returns {string}
  72. */
  73. proto.getSourceName = function getSourceName() {
  74. return klass.unwindName;
  75. };
  76. /**
  77. * Get the next source.
  78. *
  79. * @param callback
  80. * @returns {*}
  81. */
  82. proto.getNext = function getNext(callback) {
  83. if (!callback) {
  84. throw new Error(this.getSourceName() + ' #getNext() requires callback.');
  85. }
  86. if (this.expCtx.checkForInterrupt && this.expCtx.checkForInterrupt() === false) {
  87. return callback(new Error('Interrupted'));
  88. }
  89. var self = this,
  90. out = this._unwinder.getNext(),
  91. exhausted = false;
  92. async.until(
  93. function () {
  94. if (out !== null || exhausted) {
  95. return true;
  96. }
  97. return false;
  98. },
  99. function (cb) {
  100. self.source.getNext(function (err, doc) {
  101. if (err) {
  102. return cb(err);
  103. }
  104. if (doc === null) {
  105. exhausted = true;
  106. } else {
  107. self._unwinder.resetDocument(doc);
  108. out = self._unwinder.getNext();
  109. }
  110. return cb();
  111. });
  112. },
  113. function(err) {
  114. if (err) {
  115. return callback(err);
  116. }
  117. return callback(null, out);
  118. }
  119. );
  120. return out;
  121. };
  122. /**
  123. * Serialize the data.
  124. *
  125. * @param explain
  126. * @returns {{}}
  127. */
  128. proto.serialize = function serialize(explain) {
  129. if (!this._unwindPath) {
  130. throw new Error('unwind path does not exist!');
  131. }
  132. var doc = {};
  133. doc[this.getSourceName()] = this._unwindPath.getPath(true);
  134. return doc;
  135. };
  136. /**
  137. * Get the fields this operation needs to do its job.
  138. *
  139. * @param deps
  140. * @returns {DocumentSource.GetDepsReturn.SEE_NEXT|*}
  141. */
  142. proto.getDependencies = function getDependencies(deps) {
  143. if (!this._unwindPath) {
  144. throw new Error('unwind path does not exist!');
  145. }
  146. deps[this._unwindPath.getPath(false)] = 1;
  147. return DocumentSource.GetDepsReturn.SEE_NEXT;
  148. };
  149. /**
  150. * Unwind path.
  151. *
  152. * @param fieldPath
  153. */
  154. proto.unwindPath = function unwindPath(fieldPath) {
  155. if (this._unwindPath) {
  156. throw new Error(this.getSourceName() + ' can\'t unwind more than one path; code 15979');
  157. }
  158. // Record the unwind path.
  159. this._unwindPath = new FieldPath(fieldPath);
  160. this._unwinder = new klass.Unwinder(fieldPath);
  161. };
  162. /**
  163. * Creates a new UnwindDocumentSource with the input path as the path to unwind
  164. * @param {String} JsonElement this thing is *called* Json, but it expects a string
  165. **/
  166. klass.createFromJson = function createFromJson(jsonElement, ctx) {
  167. if (jsonElement.constructor !== String) {
  168. throw new Error('the ' + klass.unwindName + ' field path must be specified as a string; code 15981');
  169. }
  170. var pathString = Expression.removeFieldPrefix(jsonElement),
  171. unwind = new UnwindDocumentSource(ctx);
  172. unwind.unwindPath(pathString);
  173. return unwind;
  174. };