You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

847 lines
17 KiB

  1. /*!
  2. * Module dependencies.
  3. */
  4. var ObjectId = require('./types/objectid');
  5. var cloneRegExp = require('regexp-clone');
  6. var sliced = require('sliced');
  7. var mpath = require('mpath');
  8. var ms = require('ms');
  9. var MongooseBuffer;
  10. var MongooseArray;
  11. var Document;
  12. /*!
  13. * Produces a collection name from model `name`.
  14. *
  15. * @param {String} name a model name
  16. * @return {String} a collection name
  17. * @api private
  18. */
  19. exports.toCollectionName = function(name, options) {
  20. options = options || {};
  21. if (name === 'system.profile') {
  22. return name;
  23. }
  24. if (name === 'system.indexes') {
  25. return name;
  26. }
  27. if (options.pluralization === false) {
  28. return name;
  29. }
  30. return pluralize(name.toLowerCase());
  31. };
  32. /**
  33. * Pluralization rules.
  34. *
  35. * These rules are applied while processing the argument to `toCollectionName`.
  36. *
  37. * @deprecated remove in 4.x gh-1350
  38. */
  39. exports.pluralization = [
  40. [/(m)an$/gi, '$1en'],
  41. [/(pe)rson$/gi, '$1ople'],
  42. [/(child)$/gi, '$1ren'],
  43. [/^(ox)$/gi, '$1en'],
  44. [/(ax|test)is$/gi, '$1es'],
  45. [/(octop|vir)us$/gi, '$1i'],
  46. [/(alias|status)$/gi, '$1es'],
  47. [/(bu)s$/gi, '$1ses'],
  48. [/(buffal|tomat|potat)o$/gi, '$1oes'],
  49. [/([ti])um$/gi, '$1a'],
  50. [/sis$/gi, 'ses'],
  51. [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
  52. [/(hive)$/gi, '$1s'],
  53. [/([^aeiouy]|qu)y$/gi, '$1ies'],
  54. [/(x|ch|ss|sh)$/gi, '$1es'],
  55. [/(matr|vert|ind)ix|ex$/gi, '$1ices'],
  56. [/([m|l])ouse$/gi, '$1ice'],
  57. [/(kn|w|l)ife$/gi, '$1ives'],
  58. [/(quiz)$/gi, '$1zes'],
  59. [/s$/gi, 's'],
  60. [/([^a-z])$/, '$1'],
  61. [/$/gi, 's']
  62. ];
  63. var rules = exports.pluralization;
  64. /**
  65. * Uncountable words.
  66. *
  67. * These words are applied while processing the argument to `toCollectionName`.
  68. * @api public
  69. */
  70. exports.uncountables = [
  71. 'advice',
  72. 'energy',
  73. 'excretion',
  74. 'digestion',
  75. 'cooperation',
  76. 'health',
  77. 'justice',
  78. 'labour',
  79. 'machinery',
  80. 'equipment',
  81. 'information',
  82. 'pollution',
  83. 'sewage',
  84. 'paper',
  85. 'money',
  86. 'species',
  87. 'series',
  88. 'rain',
  89. 'rice',
  90. 'fish',
  91. 'sheep',
  92. 'moose',
  93. 'deer',
  94. 'news',
  95. 'expertise',
  96. 'status',
  97. 'media'
  98. ];
  99. var uncountables = exports.uncountables;
  100. /*!
  101. * Pluralize function.
  102. *
  103. * @author TJ Holowaychuk (extracted from _ext.js_)
  104. * @param {String} string to pluralize
  105. * @api private
  106. */
  107. function pluralize(str) {
  108. var found;
  109. if (!~uncountables.indexOf(str.toLowerCase())) {
  110. found = rules.filter(function(rule) {
  111. return str.match(rule[0]);
  112. });
  113. if (found[0]) {
  114. return str.replace(found[0][0], found[0][1]);
  115. }
  116. }
  117. return str;
  118. }
  119. /*!
  120. * Determines if `a` and `b` are deep equal.
  121. *
  122. * Modified from node/lib/assert.js
  123. *
  124. * @param {any} a a value to compare to `b`
  125. * @param {any} b a value to compare to `a`
  126. * @return {Boolean}
  127. * @api private
  128. */
  129. exports.deepEqual = function deepEqual(a, b) {
  130. if (a === b) {
  131. return true;
  132. }
  133. if (a instanceof Date && b instanceof Date) {
  134. return a.getTime() === b.getTime();
  135. }
  136. if (a instanceof ObjectId && b instanceof ObjectId) {
  137. return a.toString() === b.toString();
  138. }
  139. if (a instanceof RegExp && b instanceof RegExp) {
  140. return a.source === b.source &&
  141. a.ignoreCase === b.ignoreCase &&
  142. a.multiline === b.multiline &&
  143. a.global === b.global;
  144. }
  145. if (typeof a !== 'object' && typeof b !== 'object') {
  146. return a == b;
  147. }
  148. if (a === null || b === null || a === undefined || b === undefined) {
  149. return false;
  150. }
  151. if (a.prototype !== b.prototype) {
  152. return false;
  153. }
  154. // Handle MongooseNumbers
  155. if (a instanceof Number && b instanceof Number) {
  156. return a.valueOf() === b.valueOf();
  157. }
  158. if (Buffer.isBuffer(a)) {
  159. return exports.buffer.areEqual(a, b);
  160. }
  161. if (isMongooseObject(a)) {
  162. a = a.toObject();
  163. }
  164. if (isMongooseObject(b)) {
  165. b = b.toObject();
  166. }
  167. try {
  168. var ka = Object.keys(a),
  169. kb = Object.keys(b),
  170. key, i;
  171. } catch (e) {
  172. // happens when one is a string literal and the other isn't
  173. return false;
  174. }
  175. // having the same number of owned properties (keys incorporates
  176. // hasOwnProperty)
  177. if (ka.length !== kb.length) {
  178. return false;
  179. }
  180. // the same set of keys (although not necessarily the same order),
  181. ka.sort();
  182. kb.sort();
  183. // ~~~cheap key test
  184. for (i = ka.length - 1; i >= 0; i--) {
  185. if (ka[i] !== kb[i]) {
  186. return false;
  187. }
  188. }
  189. // equivalent values for every corresponding key, and
  190. // ~~~possibly expensive deep test
  191. for (i = ka.length - 1; i >= 0; i--) {
  192. key = ka[i];
  193. if (!deepEqual(a[key], b[key])) {
  194. return false;
  195. }
  196. }
  197. return true;
  198. };
  199. /*!
  200. * Object clone with Mongoose natives support.
  201. *
  202. * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible.
  203. *
  204. * Functions are never cloned.
  205. *
  206. * @param {Object} obj the object to clone
  207. * @param {Object} options
  208. * @return {Object} the cloned object
  209. * @api private
  210. */
  211. exports.clone = function clone(obj, options) {
  212. if (obj === undefined || obj === null) {
  213. return obj;
  214. }
  215. if (Array.isArray(obj)) {
  216. return cloneArray(obj, options);
  217. }
  218. if (isMongooseObject(obj)) {
  219. if (options && options.json && typeof obj.toJSON === 'function') {
  220. return obj.toJSON(options);
  221. }
  222. return obj.toObject(options);
  223. }
  224. if (obj.constructor) {
  225. switch (exports.getFunctionName(obj.constructor)) {
  226. case 'Object':
  227. return cloneObject(obj, options);
  228. case 'Date':
  229. return new obj.constructor(+obj);
  230. case 'RegExp':
  231. return cloneRegExp(obj);
  232. default:
  233. // ignore
  234. break;
  235. }
  236. }
  237. if (obj instanceof ObjectId) {
  238. return new ObjectId(obj.id);
  239. }
  240. if (!obj.constructor && exports.isObject(obj)) {
  241. // object created with Object.create(null)
  242. return cloneObject(obj, options);
  243. }
  244. if (obj.valueOf) {
  245. return obj.valueOf();
  246. }
  247. };
  248. var clone = exports.clone;
  249. /*!
  250. * ignore
  251. */
  252. function cloneObject(obj, options) {
  253. var retainKeyOrder = options && options.retainKeyOrder,
  254. minimize = options && options.minimize,
  255. ret = {},
  256. hasKeys,
  257. keys,
  258. val,
  259. k,
  260. i;
  261. if (retainKeyOrder) {
  262. for (k in obj) {
  263. val = clone(obj[k], options);
  264. if (!minimize || (typeof val !== 'undefined')) {
  265. hasKeys || (hasKeys = true);
  266. ret[k] = val;
  267. }
  268. }
  269. } else {
  270. // faster
  271. keys = Object.keys(obj);
  272. i = keys.length;
  273. while (i--) {
  274. k = keys[i];
  275. val = clone(obj[k], options);
  276. if (!minimize || (typeof val !== 'undefined')) {
  277. if (!hasKeys) {
  278. hasKeys = true;
  279. }
  280. ret[k] = val;
  281. }
  282. }
  283. }
  284. return minimize
  285. ? hasKeys && ret
  286. : ret;
  287. }
  288. function cloneArray(arr, options) {
  289. var ret = [];
  290. for (var i = 0, l = arr.length; i < l; i++) {
  291. ret.push(clone(arr[i], options));
  292. }
  293. return ret;
  294. }
  295. /*!
  296. * Shallow copies defaults into options.
  297. *
  298. * @param {Object} defaults
  299. * @param {Object} options
  300. * @return {Object} the merged object
  301. * @api private
  302. */
  303. exports.options = function(defaults, options) {
  304. var keys = Object.keys(defaults),
  305. i = keys.length,
  306. k;
  307. options = options || {};
  308. while (i--) {
  309. k = keys[i];
  310. if (!(k in options)) {
  311. options[k] = defaults[k];
  312. }
  313. }
  314. return options;
  315. };
  316. /*!
  317. * Generates a random string
  318. *
  319. * @api private
  320. */
  321. exports.random = function() {
  322. return Math.random().toString().substr(3);
  323. };
  324. /*!
  325. * Merges `from` into `to` without overwriting existing properties.
  326. *
  327. * @param {Object} to
  328. * @param {Object} from
  329. * @api private
  330. */
  331. exports.merge = function merge(to, from) {
  332. var keys = Object.keys(from),
  333. i = keys.length,
  334. key;
  335. while (i--) {
  336. key = keys[i];
  337. if (typeof to[key] === 'undefined') {
  338. to[key] = from[key];
  339. } else if (exports.isObject(from[key])) {
  340. merge(to[key], from[key]);
  341. }
  342. }
  343. };
  344. /*!
  345. * toString helper
  346. */
  347. var toString = Object.prototype.toString;
  348. /*!
  349. * Applies toObject recursively.
  350. *
  351. * @param {Document|Array|Object} obj
  352. * @return {Object}
  353. * @api private
  354. */
  355. exports.toObject = function toObject(obj) {
  356. Document || (Document = require('./document'));
  357. var ret;
  358. if (exports.isNullOrUndefined(obj)) {
  359. return obj;
  360. }
  361. if (obj instanceof Document) {
  362. return obj.toObject();
  363. }
  364. if (Array.isArray(obj)) {
  365. ret = [];
  366. for (var i = 0, len = obj.length; i < len; ++i) {
  367. ret.push(toObject(obj[i]));
  368. }
  369. return ret;
  370. }
  371. if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') ||
  372. (!obj.constructor && exports.isObject(obj))) {
  373. ret = {};
  374. for (var k in obj) {
  375. ret[k] = toObject(obj[k]);
  376. }
  377. return ret;
  378. }
  379. return obj;
  380. };
  381. /*!
  382. * Determines if `arg` is an object.
  383. *
  384. * @param {Object|Array|String|Function|RegExp|any} arg
  385. * @api private
  386. * @return {Boolean}
  387. */
  388. exports.isObject = function(arg) {
  389. if (Buffer.isBuffer(arg)) {
  390. return true;
  391. }
  392. return toString.call(arg) === '[object Object]';
  393. };
  394. /*!
  395. * A faster Array.prototype.slice.call(arguments) alternative
  396. * @api private
  397. */
  398. exports.args = sliced;
  399. /*!
  400. * process.nextTick helper.
  401. *
  402. * Wraps `callback` in a try/catch + nextTick.
  403. *
  404. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  405. *
  406. * @param {Function} callback
  407. * @api private
  408. */
  409. exports.tick = function tick(callback) {
  410. if (typeof callback !== 'function') {
  411. return;
  412. }
  413. return function() {
  414. try {
  415. callback.apply(this, arguments);
  416. } catch (err) {
  417. // only nextTick on err to get out of
  418. // the event loop and avoid state corruption.
  419. process.nextTick(function() {
  420. throw err;
  421. });
  422. }
  423. };
  424. };
  425. /*!
  426. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  427. *
  428. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  429. *
  430. * @param {any} v
  431. * @api private
  432. */
  433. exports.isMongooseObject = function(v) {
  434. Document || (Document = require('./document'));
  435. MongooseArray || (MongooseArray = require('./types').Array);
  436. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  437. return v instanceof Document ||
  438. (v && v.isMongooseArray) ||
  439. (v && v.isMongooseBuffer);
  440. };
  441. var isMongooseObject = exports.isMongooseObject;
  442. /*!
  443. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  444. *
  445. * @param {Object} object
  446. * @api private
  447. */
  448. exports.expires = function expires(object) {
  449. if (!(object && object.constructor.name === 'Object')) {
  450. return;
  451. }
  452. if (!('expires' in object)) {
  453. return;
  454. }
  455. var when;
  456. if (typeof object.expires !== 'string') {
  457. when = object.expires;
  458. } else {
  459. when = Math.round(ms(object.expires) / 1000);
  460. }
  461. object.expireAfterSeconds = when;
  462. delete object.expires;
  463. };
  464. /*!
  465. * Populate options constructor
  466. */
  467. function PopulateOptions(path, select, match, options, model, subPopulate) {
  468. this.path = path;
  469. this.match = match;
  470. this.select = select;
  471. this.options = options;
  472. this.model = model;
  473. if (typeof subPopulate === 'object') {
  474. this.populate = subPopulate;
  475. }
  476. this._docs = {};
  477. }
  478. // make it compatible with utils.clone
  479. PopulateOptions.prototype.constructor = Object;
  480. // expose
  481. exports.PopulateOptions = PopulateOptions;
  482. /*!
  483. * populate helper
  484. */
  485. exports.populate = function populate(path, select, model, match, options, subPopulate) {
  486. // The order of select/conditions args is opposite Model.find but
  487. // necessary to keep backward compatibility (select could be
  488. // an array, string, or object literal).
  489. // might have passed an object specifying all arguments
  490. if (arguments.length === 1) {
  491. if (path instanceof PopulateOptions) {
  492. return [path];
  493. }
  494. if (Array.isArray(path)) {
  495. return path.map(function(o) {
  496. return exports.populate(o)[0];
  497. });
  498. }
  499. if (exports.isObject(path)) {
  500. match = path.match;
  501. options = path.options;
  502. select = path.select;
  503. model = path.model;
  504. subPopulate = path.populate;
  505. path = path.path;
  506. }
  507. } else if (typeof model !== 'string' && typeof model !== 'function') {
  508. options = match;
  509. match = model;
  510. model = undefined;
  511. }
  512. if (typeof path !== 'string') {
  513. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  514. }
  515. if (typeof subPopulate === 'object') {
  516. subPopulate = exports.populate(subPopulate);
  517. }
  518. var ret = [];
  519. var paths = path.split(' ');
  520. options = exports.clone(options, { retainKeyOrder: true });
  521. for (var i = 0; i < paths.length; ++i) {
  522. ret.push(new PopulateOptions(paths[i], select, match, options, model, subPopulate));
  523. }
  524. return ret;
  525. };
  526. /*!
  527. * Return the value of `obj` at the given `path`.
  528. *
  529. * @param {String} path
  530. * @param {Object} obj
  531. */
  532. exports.getValue = function(path, obj, map) {
  533. return mpath.get(path, obj, '_doc', map);
  534. };
  535. /*!
  536. * Sets the value of `obj` at the given `path`.
  537. *
  538. * @param {String} path
  539. * @param {Anything} val
  540. * @param {Object} obj
  541. */
  542. exports.setValue = function(path, val, obj, map) {
  543. mpath.set(path, val, obj, '_doc', map);
  544. };
  545. /*!
  546. * Returns an array of values from object `o`.
  547. *
  548. * @param {Object} o
  549. * @return {Array}
  550. * @private
  551. */
  552. exports.object = {};
  553. exports.object.vals = function vals(o) {
  554. var keys = Object.keys(o),
  555. i = keys.length,
  556. ret = [];
  557. while (i--) {
  558. ret.push(o[keys[i]]);
  559. }
  560. return ret;
  561. };
  562. /*!
  563. * @see exports.options
  564. */
  565. exports.object.shallowCopy = exports.options;
  566. /*!
  567. * Safer helper for hasOwnProperty checks
  568. *
  569. * @param {Object} obj
  570. * @param {String} prop
  571. */
  572. var hop = Object.prototype.hasOwnProperty;
  573. exports.object.hasOwnProperty = function(obj, prop) {
  574. return hop.call(obj, prop);
  575. };
  576. /*!
  577. * Determine if `val` is null or undefined
  578. *
  579. * @return {Boolean}
  580. */
  581. exports.isNullOrUndefined = function(val) {
  582. return val === null || val === undefined;
  583. };
  584. /*!
  585. * ignore
  586. */
  587. exports.array = {};
  588. /*!
  589. * Flattens an array.
  590. *
  591. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  592. *
  593. * @param {Array} arr
  594. * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results.
  595. * @return {Array}
  596. * @private
  597. */
  598. exports.array.flatten = function flatten(arr, filter, ret) {
  599. ret || (ret = []);
  600. arr.forEach(function(item) {
  601. if (Array.isArray(item)) {
  602. flatten(item, filter, ret);
  603. } else {
  604. if (!filter || filter(item)) {
  605. ret.push(item);
  606. }
  607. }
  608. });
  609. return ret;
  610. };
  611. /*!
  612. * Removes duplicate values from an array
  613. *
  614. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  615. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  616. * => [ObjectId("550988ba0c19d57f697dc45e")]
  617. *
  618. * @param {Array} arr
  619. * @return {Array}
  620. * @private
  621. */
  622. exports.array.unique = function(arr) {
  623. var primitives = {};
  624. var ids = {};
  625. var ret = [];
  626. var length = arr.length;
  627. for (var i = 0; i < length; ++i) {
  628. if (typeof arr[i] === 'number' || typeof arr[i] === 'string') {
  629. if (primitives[arr[i]]) {
  630. continue;
  631. }
  632. ret.push(arr[i]);
  633. primitives[arr[i]] = true;
  634. } else if (arr[i] instanceof ObjectId) {
  635. if (ids[arr[i].toString()]) {
  636. continue;
  637. }
  638. ret.push(arr[i]);
  639. ids[arr[i].toString()] = true;
  640. } else {
  641. ret.push(arr[i]);
  642. }
  643. }
  644. return ret;
  645. };
  646. /*!
  647. * Determines if two buffers are equal.
  648. *
  649. * @param {Buffer} a
  650. * @param {Object} b
  651. */
  652. exports.buffer = {};
  653. exports.buffer.areEqual = function(a, b) {
  654. if (!Buffer.isBuffer(a)) {
  655. return false;
  656. }
  657. if (!Buffer.isBuffer(b)) {
  658. return false;
  659. }
  660. if (a.length !== b.length) {
  661. return false;
  662. }
  663. for (var i = 0, len = a.length; i < len; ++i) {
  664. if (a[i] !== b[i]) {
  665. return false;
  666. }
  667. }
  668. return true;
  669. };
  670. exports.getFunctionName = function(fn) {
  671. if (fn.name) {
  672. return fn.name;
  673. }
  674. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  675. };
  676. exports.decorate = function(destination, source) {
  677. for (var key in source) {
  678. destination[key] = source[key];
  679. }
  680. };
  681. /**
  682. * merges to with a copy of from
  683. *
  684. * @param {Object} to
  685. * @param {Object} fromObj
  686. * @api private
  687. */
  688. exports.mergeClone = function(to, fromObj) {
  689. var keys = Object.keys(fromObj),
  690. i = keys.length,
  691. key;
  692. while (i--) {
  693. key = keys[i];
  694. if (typeof to[key] === 'undefined') {
  695. // make sure to retain key order here because of a bug handling the $each
  696. // operator in mongodb 2.4.4
  697. to[key] = exports.clone(fromObj[key], {retainKeyOrder: 1});
  698. } else {
  699. if (exports.isObject(fromObj[key])) {
  700. var obj = fromObj[key];
  701. if (isMongooseObject(fromObj[key]) && !fromObj[key].isMongooseBuffer) {
  702. obj = obj.toObject({ virtuals: false });
  703. }
  704. exports.mergeClone(to[key], obj);
  705. } else {
  706. // make sure to retain key order here because of a bug handling the
  707. // $each operator in mongodb 2.4.4
  708. to[key] = exports.clone(fromObj[key], {retainKeyOrder: 1});
  709. }
  710. }
  711. }
  712. };
  713. /**
  714. * Executes a function on each element of an array (like _.each)
  715. *
  716. * @param {Array} arr
  717. * @param {Function} fn
  718. * @api private
  719. */
  720. exports.each = function(arr, fn) {
  721. for (var i = 0; i < arr.length; ++i) {
  722. fn(arr[i]);
  723. }
  724. };