utils.js 20 KB

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