utils.js 21 KB

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