utils.js 23 KB

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