utils.js 20 KB

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