Ohm-Management - Projektarbeit B-ME
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.

utils.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const Decimal = require('./types/decimal128');
  6. const ObjectId = require('./types/objectid');
  7. const PromiseProvider = require('./promise_provider');
  8. const cloneRegExp = require('regexp-clone');
  9. const get = require('./helpers/get');
  10. const sliced = require('sliced');
  11. const mpath = require('mpath');
  12. const ms = require('ms');
  13. const symbols = require('./helpers/symbols');
  14. const Buffer = require('safe-buffer').Buffer;
  15. const emittedSymbol = Symbol.for('mongoose:emitted');
  16. let MongooseBuffer;
  17. let MongooseArray;
  18. let Document;
  19. const specialProperties = new Set(['__proto__', 'constructor', 'prototype']);
  20. exports.specialProperties = specialProperties;
  21. /*!
  22. * Produces a collection name from model `name`. By default, just returns
  23. * the model name
  24. *
  25. * @param {String} name a model name
  26. * @param {Function} pluralize function that pluralizes the collection name
  27. * @return {String} a collection name
  28. * @api private
  29. */
  30. exports.toCollectionName = function(name, pluralize) {
  31. if (name === 'system.profile') {
  32. return name;
  33. }
  34. if (name === 'system.indexes') {
  35. return name;
  36. }
  37. if (typeof pluralize === 'function') {
  38. return pluralize(name);
  39. }
  40. return name;
  41. };
  42. /*!
  43. * Determines if `a` and `b` are deep equal.
  44. *
  45. * Modified from node/lib/assert.js
  46. *
  47. * @param {any} a a value to compare to `b`
  48. * @param {any} b a value to compare to `a`
  49. * @return {Boolean}
  50. * @api private
  51. */
  52. exports.deepEqual = function deepEqual(a, b) {
  53. if (a === b) {
  54. return true;
  55. }
  56. if (a instanceof Date && b instanceof Date) {
  57. return a.getTime() === b.getTime();
  58. }
  59. if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) ||
  60. (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) {
  61. return a.toString() === b.toString();
  62. }
  63. if (a instanceof RegExp && b instanceof RegExp) {
  64. return a.source === b.source &&
  65. a.ignoreCase === b.ignoreCase &&
  66. a.multiline === b.multiline &&
  67. a.global === b.global;
  68. }
  69. if (typeof a !== 'object' && typeof b !== 'object') {
  70. return a == b;
  71. }
  72. if (a === null || b === null || a === undefined || b === undefined) {
  73. return false;
  74. }
  75. if (a.prototype !== b.prototype) {
  76. return false;
  77. }
  78. // Handle MongooseNumbers
  79. if (a instanceof Number && b instanceof Number) {
  80. return a.valueOf() === b.valueOf();
  81. }
  82. if (Buffer.isBuffer(a)) {
  83. return exports.buffer.areEqual(a, b);
  84. }
  85. if (isMongooseObject(a)) {
  86. a = a.toObject();
  87. }
  88. if (isMongooseObject(b)) {
  89. b = b.toObject();
  90. }
  91. let ka;
  92. let kb;
  93. let key;
  94. let i;
  95. try {
  96. ka = Object.keys(a);
  97. kb = Object.keys(b);
  98. } catch (e) {
  99. // happens when one is a string literal and the other isn't
  100. return false;
  101. }
  102. // having the same number of owned properties (keys incorporates
  103. // hasOwnProperty)
  104. if (ka.length !== kb.length) {
  105. return false;
  106. }
  107. // the same set of keys (although not necessarily the same order),
  108. ka.sort();
  109. kb.sort();
  110. // ~~~cheap key test
  111. for (i = ka.length - 1; i >= 0; i--) {
  112. if (ka[i] !== kb[i]) {
  113. return false;
  114. }
  115. }
  116. // equivalent values for every corresponding key, and
  117. // ~~~possibly expensive deep test
  118. for (i = ka.length - 1; i >= 0; i--) {
  119. key = ka[i];
  120. if (!deepEqual(a[key], b[key])) {
  121. return false;
  122. }
  123. }
  124. return true;
  125. };
  126. /*!
  127. * Get the bson type, if it exists
  128. */
  129. function isBsonType(obj, typename) {
  130. return get(obj, '_bsontype', void 0) === typename;
  131. }
  132. /*!
  133. * Get the last element of an array
  134. */
  135. exports.last = function(arr) {
  136. if (arr.length > 0) {
  137. return arr[arr.length - 1];
  138. }
  139. return void 0;
  140. };
  141. /*!
  142. * Object clone with Mongoose natives support.
  143. *
  144. * 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.
  145. *
  146. * Functions are never cloned.
  147. *
  148. * @param {Object} obj the object to clone
  149. * @param {Object} options
  150. * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize.
  151. * @return {Object} the cloned object
  152. * @api private
  153. */
  154. exports.clone = function clone(obj, options, isArrayChild) {
  155. if (obj == null) {
  156. return obj;
  157. }
  158. if (Array.isArray(obj)) {
  159. return cloneArray(obj, options);
  160. }
  161. if (isMongooseObject(obj)) {
  162. if (options && options.json && typeof obj.toJSON === 'function') {
  163. return obj.toJSON(options);
  164. }
  165. return obj.toObject(options);
  166. }
  167. if (obj.constructor) {
  168. switch (exports.getFunctionName(obj.constructor)) {
  169. case 'Object':
  170. return cloneObject(obj, options, isArrayChild);
  171. case 'Date':
  172. return new obj.constructor(+obj);
  173. case 'RegExp':
  174. return cloneRegExp(obj);
  175. default:
  176. // ignore
  177. break;
  178. }
  179. }
  180. if (obj instanceof ObjectId) {
  181. return new ObjectId(obj.id);
  182. }
  183. if (isBsonType(obj, 'Decimal128')) {
  184. if (options && options.flattenDecimals) {
  185. return obj.toJSON();
  186. }
  187. return Decimal.fromString(obj.toString());
  188. }
  189. if (!obj.constructor && exports.isObject(obj)) {
  190. // object created with Object.create(null)
  191. return cloneObject(obj, options, isArrayChild);
  192. }
  193. if (obj[symbols.schemaTypeSymbol]) {
  194. return obj.clone();
  195. }
  196. if (obj.valueOf != null) {
  197. return obj.valueOf();
  198. }
  199. return cloneObject(obj, options, isArrayChild);
  200. };
  201. const clone = exports.clone;
  202. /*!
  203. * ignore
  204. */
  205. exports.promiseOrCallback = function promiseOrCallback(callback, fn, ee) {
  206. if (typeof callback === 'function') {
  207. return fn(function(error) {
  208. if (error != null) {
  209. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  210. error[emittedSymbol] = true;
  211. ee.emit('error', error);
  212. }
  213. try {
  214. callback(error);
  215. } catch (error) {
  216. return process.nextTick(() => {
  217. throw error;
  218. });
  219. }
  220. return;
  221. }
  222. callback.apply(this, arguments);
  223. });
  224. }
  225. const Promise = PromiseProvider.get();
  226. return new Promise((resolve, reject) => {
  227. fn(function(error, res) {
  228. if (error != null) {
  229. if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) {
  230. error[emittedSymbol] = true;
  231. ee.emit('error', error);
  232. }
  233. return reject(error);
  234. }
  235. if (arguments.length > 2) {
  236. return resolve(Array.prototype.slice.call(arguments, 1));
  237. }
  238. resolve(res);
  239. });
  240. });
  241. };
  242. /*!
  243. * ignore
  244. */
  245. function cloneObject(obj, options, isArrayChild) {
  246. const minimize = options && options.minimize;
  247. const ret = {};
  248. let hasKeys;
  249. for (const k in obj) {
  250. if (specialProperties.has(k)) {
  251. continue;
  252. }
  253. // Don't pass `isArrayChild` down
  254. const val = clone(obj[k], options);
  255. if (!minimize || (typeof val !== 'undefined')) {
  256. hasKeys || (hasKeys = true);
  257. ret[k] = val;
  258. }
  259. }
  260. return minimize && !isArrayChild ? hasKeys && ret : ret;
  261. }
  262. function cloneArray(arr, options) {
  263. const ret = [];
  264. for (let i = 0, l = arr.length; i < l; i++) {
  265. ret.push(clone(arr[i], options, true));
  266. }
  267. return ret;
  268. }
  269. /*!
  270. * Shallow copies defaults into options.
  271. *
  272. * @param {Object} defaults
  273. * @param {Object} options
  274. * @return {Object} the merged object
  275. * @api private
  276. */
  277. exports.options = function(defaults, options) {
  278. const keys = Object.keys(defaults);
  279. let i = keys.length;
  280. let k;
  281. options = options || {};
  282. while (i--) {
  283. k = keys[i];
  284. if (!(k in options)) {
  285. options[k] = defaults[k];
  286. }
  287. }
  288. return options;
  289. };
  290. /*!
  291. * Generates a random string
  292. *
  293. * @api private
  294. */
  295. exports.random = function() {
  296. return Math.random().toString().substr(3);
  297. };
  298. /*!
  299. * Merges `from` into `to` without overwriting existing properties.
  300. *
  301. * @param {Object} to
  302. * @param {Object} from
  303. * @api private
  304. */
  305. exports.merge = function merge(to, from, options, path) {
  306. options = options || {};
  307. const keys = Object.keys(from);
  308. let i = 0;
  309. const len = keys.length;
  310. let key;
  311. path = path || '';
  312. const omitNested = options.omitNested || {};
  313. while (i < len) {
  314. key = keys[i++];
  315. if (options.omit && options.omit[key]) {
  316. continue;
  317. }
  318. if (omitNested[path]) {
  319. continue;
  320. }
  321. if (specialProperties.has(key)) {
  322. continue;
  323. }
  324. if (to[key] == null) {
  325. to[key] = from[key];
  326. } else if (exports.isObject(from[key])) {
  327. if (!exports.isObject(to[key])) {
  328. to[key] = {};
  329. }
  330. if (from[key] != null) {
  331. if (from[key].instanceOfSchema) {
  332. to[key] = from[key].clone();
  333. continue;
  334. } else if (from[key] instanceof ObjectId) {
  335. to[key] = new ObjectId(from[key]);
  336. continue;
  337. }
  338. }
  339. merge(to[key], from[key], options, path ? path + '.' + key : key);
  340. } else if (options.overwrite) {
  341. to[key] = from[key];
  342. }
  343. }
  344. };
  345. /*!
  346. * Applies toObject recursively.
  347. *
  348. * @param {Document|Array|Object} obj
  349. * @return {Object}
  350. * @api private
  351. */
  352. exports.toObject = function toObject(obj) {
  353. Document || (Document = require('./document'));
  354. let ret;
  355. if (obj == null) {
  356. return obj;
  357. }
  358. if (obj instanceof Document) {
  359. return obj.toObject();
  360. }
  361. if (Array.isArray(obj)) {
  362. ret = [];
  363. for (let i = 0, len = obj.length; i < len; ++i) {
  364. ret.push(toObject(obj[i]));
  365. }
  366. return ret;
  367. }
  368. if (exports.isPOJO(obj)) {
  369. ret = {};
  370. for (const k in obj) {
  371. if (specialProperties.has(k)) {
  372. continue;
  373. }
  374. ret[k] = toObject(obj[k]);
  375. }
  376. return ret;
  377. }
  378. return obj;
  379. };
  380. /*!
  381. * Determines if `arg` is an object.
  382. *
  383. * @param {Object|Array|String|Function|RegExp|any} arg
  384. * @api private
  385. * @return {Boolean}
  386. */
  387. exports.isObject = function(arg) {
  388. if (Buffer.isBuffer(arg)) {
  389. return true;
  390. }
  391. return Object.prototype.toString.call(arg) === '[object Object]';
  392. };
  393. /*!
  394. * Determines if `arg` is a plain old JavaScript object (POJO). Specifically,
  395. * `arg` must be an object but not an instance of any special class, like String,
  396. * ObjectId, etc.
  397. *
  398. * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
  399. *
  400. * @param {Object|Array|String|Function|RegExp|any} arg
  401. * @api private
  402. * @return {Boolean}
  403. */
  404. exports.isPOJO = function(arg) {
  405. if (arg == null || typeof arg !== 'object') {
  406. return false;
  407. }
  408. const proto = Object.getPrototypeOf(arg);
  409. // Prototype may be null if you used `Object.create(null)`
  410. // Checking `proto`'s constructor is safe because `getPrototypeOf()`
  411. // explicitly crosses the boundary from object data to object metadata
  412. return !proto || proto.constructor.name === 'Object';
  413. };
  414. /*!
  415. * A faster Array.prototype.slice.call(arguments) alternative
  416. * @api private
  417. */
  418. exports.args = sliced;
  419. /*!
  420. * process.nextTick helper.
  421. *
  422. * Wraps `callback` in a try/catch + nextTick.
  423. *
  424. * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.
  425. *
  426. * @param {Function} callback
  427. * @api private
  428. */
  429. exports.tick = function tick(callback) {
  430. if (typeof callback !== 'function') {
  431. return;
  432. }
  433. return function() {
  434. try {
  435. callback.apply(this, arguments);
  436. } catch (err) {
  437. // only nextTick on err to get out of
  438. // the event loop and avoid state corruption.
  439. process.nextTick(function() {
  440. throw err;
  441. });
  442. }
  443. };
  444. };
  445. /*!
  446. * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
  447. *
  448. * This is for compatibility with libs like Date.js which do foolish things to Natives.
  449. *
  450. * @param {any} v
  451. * @api private
  452. */
  453. exports.isMongooseObject = function(v) {
  454. Document || (Document = require('./document'));
  455. MongooseArray || (MongooseArray = require('./types').Array);
  456. MongooseBuffer || (MongooseBuffer = require('./types').Buffer);
  457. if (v == null) {
  458. return false;
  459. }
  460. return v.$__ != null || // Document
  461. v.isMongooseArray || // Array or Document Array
  462. v.isMongooseBuffer || // Buffer
  463. v.$isMongooseMap; // Map
  464. };
  465. const isMongooseObject = exports.isMongooseObject;
  466. /*!
  467. * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
  468. *
  469. * @param {Object} object
  470. * @api private
  471. */
  472. exports.expires = function expires(object) {
  473. if (!(object && object.constructor.name === 'Object')) {
  474. return;
  475. }
  476. if (!('expires' in object)) {
  477. return;
  478. }
  479. let when;
  480. if (typeof object.expires !== 'string') {
  481. when = object.expires;
  482. } else {
  483. when = Math.round(ms(object.expires) / 1000);
  484. }
  485. object.expireAfterSeconds = when;
  486. delete object.expires;
  487. };
  488. /*!
  489. * Populate options constructor
  490. */
  491. function PopulateOptions(obj) {
  492. this.path = obj.path;
  493. this.match = obj.match;
  494. this.select = obj.select;
  495. this.options = obj.options;
  496. this.model = obj.model;
  497. if (typeof obj.subPopulate === 'object') {
  498. this.populate = obj.subPopulate;
  499. }
  500. if (obj.justOne != null) {
  501. this.justOne = obj.justOne;
  502. }
  503. if (obj.count != null) {
  504. this.count = obj.count;
  505. }
  506. this._docs = {};
  507. }
  508. // make it compatible with utils.clone
  509. PopulateOptions.prototype.constructor = Object;
  510. // expose
  511. exports.PopulateOptions = PopulateOptions;
  512. /*!
  513. * populate helper
  514. */
  515. exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) {
  516. // The order of select/conditions args is opposite Model.find but
  517. // necessary to keep backward compatibility (select could be
  518. // an array, string, or object literal).
  519. function makeSingles(arr) {
  520. const ret = [];
  521. arr.forEach(function(obj) {
  522. if (/[\s]/.test(obj.path)) {
  523. const paths = obj.path.split(' ');
  524. paths.forEach(function(p) {
  525. const copy = Object.assign({}, obj);
  526. copy.path = p;
  527. ret.push(copy);
  528. });
  529. } else {
  530. ret.push(obj);
  531. }
  532. });
  533. return ret;
  534. }
  535. // might have passed an object specifying all arguments
  536. if (arguments.length === 1) {
  537. if (path instanceof PopulateOptions) {
  538. return [path];
  539. }
  540. if (Array.isArray(path)) {
  541. const singles = makeSingles(path);
  542. return singles.map(function(o) {
  543. if (o.populate && !(o.match || o.options)) {
  544. return exports.populate(o)[0];
  545. } else {
  546. return exports.populate(o)[0];
  547. }
  548. });
  549. }
  550. if (exports.isObject(path)) {
  551. match = path.match;
  552. options = path.options;
  553. select = path.select;
  554. model = path.model;
  555. subPopulate = path.populate;
  556. justOne = path.justOne;
  557. path = path.path;
  558. count = path.count;
  559. }
  560. } else if (typeof model === 'object') {
  561. options = match;
  562. match = model;
  563. model = undefined;
  564. }
  565. if (typeof path !== 'string') {
  566. throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
  567. }
  568. if (Array.isArray(subPopulate)) {
  569. const ret = [];
  570. subPopulate.forEach(function(obj) {
  571. if (/[\s]/.test(obj.path)) {
  572. const copy = Object.assign({}, obj);
  573. const paths = copy.path.split(' ');
  574. paths.forEach(function(p) {
  575. copy.path = p;
  576. ret.push(exports.populate(copy)[0]);
  577. });
  578. } else {
  579. ret.push(exports.populate(obj)[0]);
  580. }
  581. });
  582. subPopulate = exports.populate(ret);
  583. } else if (typeof subPopulate === 'object') {
  584. subPopulate = exports.populate(subPopulate);
  585. }
  586. const ret = [];
  587. const paths = path.split(' ');
  588. options = exports.clone(options);
  589. for (let i = 0; i < paths.length; ++i) {
  590. ret.push(new PopulateOptions({
  591. path: paths[i],
  592. select: select,
  593. match: match,
  594. options: options,
  595. model: model,
  596. subPopulate: subPopulate,
  597. justOne: justOne,
  598. count: count
  599. }));
  600. }
  601. return ret;
  602. };
  603. /*!
  604. * Return the value of `obj` at the given `path`.
  605. *
  606. * @param {String} path
  607. * @param {Object} obj
  608. */
  609. exports.getValue = function(path, obj, map) {
  610. return mpath.get(path, obj, '_doc', map);
  611. };
  612. /*!
  613. * Sets the value of `obj` at the given `path`.
  614. *
  615. * @param {String} path
  616. * @param {Anything} val
  617. * @param {Object} obj
  618. */
  619. exports.setValue = function(path, val, obj, map, _copying) {
  620. mpath.set(path, val, obj, '_doc', map, _copying);
  621. };
  622. /*!
  623. * Returns an array of values from object `o`.
  624. *
  625. * @param {Object} o
  626. * @return {Array}
  627. * @private
  628. */
  629. exports.object = {};
  630. exports.object.vals = function vals(o) {
  631. const keys = Object.keys(o);
  632. let i = keys.length;
  633. const ret = [];
  634. while (i--) {
  635. ret.push(o[keys[i]]);
  636. }
  637. return ret;
  638. };
  639. /*!
  640. * @see exports.options
  641. */
  642. exports.object.shallowCopy = exports.options;
  643. /*!
  644. * Safer helper for hasOwnProperty checks
  645. *
  646. * @param {Object} obj
  647. * @param {String} prop
  648. */
  649. const hop = Object.prototype.hasOwnProperty;
  650. exports.object.hasOwnProperty = function(obj, prop) {
  651. return hop.call(obj, prop);
  652. };
  653. /*!
  654. * Determine if `val` is null or undefined
  655. *
  656. * @return {Boolean}
  657. */
  658. exports.isNullOrUndefined = function(val) {
  659. return val === null || val === undefined;
  660. };
  661. /*!
  662. * ignore
  663. */
  664. exports.array = {};
  665. /*!
  666. * Flattens an array.
  667. *
  668. * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4]
  669. *
  670. * @param {Array} arr
  671. * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results.
  672. * @return {Array}
  673. * @private
  674. */
  675. exports.array.flatten = function flatten(arr, filter, ret) {
  676. ret || (ret = []);
  677. arr.forEach(function(item) {
  678. if (Array.isArray(item)) {
  679. flatten(item, filter, ret);
  680. } else {
  681. if (!filter || filter(item)) {
  682. ret.push(item);
  683. }
  684. }
  685. });
  686. return ret;
  687. };
  688. /*!
  689. * Removes duplicate values from an array
  690. *
  691. * [1, 2, 3, 3, 5] => [1, 2, 3, 5]
  692. * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ]
  693. * => [ObjectId("550988ba0c19d57f697dc45e")]
  694. *
  695. * @param {Array} arr
  696. * @return {Array}
  697. * @private
  698. */
  699. exports.array.unique = function(arr) {
  700. const primitives = {};
  701. const ids = {};
  702. const ret = [];
  703. const length = arr.length;
  704. for (let i = 0; i < length; ++i) {
  705. if (typeof arr[i] === 'number' || typeof arr[i] === 'string' || arr[i] == null) {
  706. if (primitives[arr[i]]) {
  707. continue;
  708. }
  709. ret.push(arr[i]);
  710. primitives[arr[i]] = true;
  711. } else if (arr[i] instanceof ObjectId) {
  712. if (ids[arr[i].toString()]) {
  713. continue;
  714. }
  715. ret.push(arr[i]);
  716. ids[arr[i].toString()] = true;
  717. } else {
  718. ret.push(arr[i]);
  719. }
  720. }
  721. return ret;
  722. };
  723. /*!
  724. * Determines if two buffers are equal.
  725. *
  726. * @param {Buffer} a
  727. * @param {Object} b
  728. */
  729. exports.buffer = {};
  730. exports.buffer.areEqual = function(a, b) {
  731. if (!Buffer.isBuffer(a)) {
  732. return false;
  733. }
  734. if (!Buffer.isBuffer(b)) {
  735. return false;
  736. }
  737. if (a.length !== b.length) {
  738. return false;
  739. }
  740. for (let i = 0, len = a.length; i < len; ++i) {
  741. if (a[i] !== b[i]) {
  742. return false;
  743. }
  744. }
  745. return true;
  746. };
  747. exports.getFunctionName = function(fn) {
  748. if (fn.name) {
  749. return fn.name;
  750. }
  751. return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1];
  752. };
  753. /*!
  754. * Decorate buffers
  755. */
  756. exports.decorate = function(destination, source) {
  757. for (const key in source) {
  758. if (specialProperties.has(key)) {
  759. continue;
  760. }
  761. destination[key] = source[key];
  762. }
  763. };
  764. /**
  765. * merges to with a copy of from
  766. *
  767. * @param {Object} to
  768. * @param {Object} fromObj
  769. * @api private
  770. */
  771. exports.mergeClone = function(to, fromObj) {
  772. if (isMongooseObject(fromObj)) {
  773. fromObj = fromObj.toObject({
  774. transform: false,
  775. virtuals: false,
  776. depopulate: true,
  777. getters: false,
  778. flattenDecimals: false
  779. });
  780. }
  781. const keys = Object.keys(fromObj);
  782. const len = keys.length;
  783. let i = 0;
  784. let key;
  785. while (i < len) {
  786. key = keys[i++];
  787. if (specialProperties.has(key)) {
  788. continue;
  789. }
  790. if (typeof to[key] === 'undefined') {
  791. to[key] = exports.clone(fromObj[key], {
  792. transform: false,
  793. virtuals: false,
  794. depopulate: true,
  795. getters: false,
  796. flattenDecimals: false
  797. });
  798. } else {
  799. let val = fromObj[key];
  800. if (val != null && val.valueOf && !(val instanceof Date)) {
  801. val = val.valueOf();
  802. }
  803. if (exports.isObject(val)) {
  804. let obj = val;
  805. if (isMongooseObject(val) && !val.isMongooseBuffer) {
  806. obj = obj.toObject({
  807. transform: false,
  808. virtuals: false,
  809. depopulate: true,
  810. getters: false,
  811. flattenDecimals: false
  812. });
  813. }
  814. if (val.isMongooseBuffer) {
  815. obj = Buffer.from(obj);
  816. }
  817. exports.mergeClone(to[key], obj);
  818. } else {
  819. to[key] = exports.clone(val, {
  820. flattenDecimals: false
  821. });
  822. }
  823. }
  824. }
  825. };
  826. /**
  827. * Executes a function on each element of an array (like _.each)
  828. *
  829. * @param {Array} arr
  830. * @param {Function} fn
  831. * @api private
  832. */
  833. exports.each = function(arr, fn) {
  834. for (let i = 0; i < arr.length; ++i) {
  835. fn(arr[i]);
  836. }
  837. };
  838. /*!
  839. * ignore
  840. */
  841. exports.noop = function() {};