Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

assignRawDocsToIdStructure.js 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. module.exports = assignRawDocsToIdStructure;
  3. /*!
  4. * Assign `vals` returned by mongo query to the `rawIds`
  5. * structure returned from utils.getVals() honoring
  6. * query sort order if specified by user.
  7. *
  8. * This can be optimized.
  9. *
  10. * Rules:
  11. *
  12. * if the value of the path is not an array, use findOne rules, else find.
  13. * for findOne the results are assigned directly to doc path (including null results).
  14. * for find, if user specified sort order, results are assigned directly
  15. * else documents are put back in original order of array if found in results
  16. *
  17. * @param {Array} rawIds
  18. * @param {Array} vals
  19. * @param {Boolean} sort
  20. * @api private
  21. */
  22. function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) {
  23. // honor user specified sort order
  24. const newOrder = [];
  25. const sorting = options.sort && rawIds.length > 1;
  26. let doc;
  27. let sid;
  28. let id;
  29. for (let i = 0; i < rawIds.length; ++i) {
  30. id = rawIds[i];
  31. if (Array.isArray(id)) {
  32. // handle [ [id0, id2], [id3] ]
  33. assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true);
  34. newOrder.push(id);
  35. continue;
  36. }
  37. if (id === null && !sorting) {
  38. // keep nulls for findOne unless sorting, which always
  39. // removes them (backward compat)
  40. newOrder.push(id);
  41. continue;
  42. }
  43. sid = String(id);
  44. doc = resultDocs[sid];
  45. // If user wants separate copies of same doc, use this option
  46. if (options.clone) {
  47. doc = doc.constructor.hydrate(doc._doc);
  48. }
  49. if (recursed) {
  50. if (doc) {
  51. if (sorting) {
  52. newOrder[resultOrder[sid]] = doc;
  53. } else {
  54. newOrder.push(doc);
  55. }
  56. } else {
  57. newOrder.push(id);
  58. }
  59. } else {
  60. // apply findOne behavior - if document in results, assign, else assign null
  61. newOrder[i] = doc || null;
  62. }
  63. }
  64. rawIds.length = 0;
  65. if (newOrder.length) {
  66. // reassign the documents based on corrected order
  67. // forEach skips over sparse entries in arrays so we
  68. // can safely use this to our advantage dealing with sorted
  69. // result sets too.
  70. newOrder.forEach(function(doc, i) {
  71. rawIds[i] = doc;
  72. });
  73. }
  74. }