completeMany.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const helpers = require('../../queryhelpers');
  3. const immediate = require('../immediate');
  4. module.exports = completeMany;
  5. /*!
  6. * Given a model and an array of docs, hydrates all the docs to be instances
  7. * of the model. Used to initialize docs returned from the db from `find()`
  8. *
  9. * @param {Model} model
  10. * @param {Array} docs
  11. * @param {Object} fields the projection used, including `select` from schemas
  12. * @param {Object} userProvidedFields the user-specified projection
  13. * @param {Object} opts
  14. * @param {Array} [opts.populated]
  15. * @param {ClientSession} [opts.session]
  16. * @param {Function} callback
  17. */
  18. function completeMany(model, docs, fields, userProvidedFields, opts, callback) {
  19. const arr = [];
  20. let count = docs.length;
  21. const len = count;
  22. let error = null;
  23. function init(_error) {
  24. if (_error != null) {
  25. error = error || _error;
  26. }
  27. if (error != null) {
  28. --count || immediate(() => callback(error));
  29. return;
  30. }
  31. --count || immediate(() => callback(error, arr));
  32. }
  33. for (let i = 0; i < len; ++i) {
  34. arr[i] = helpers.createModel(model, docs[i], fields, userProvidedFields);
  35. try {
  36. arr[i].$init(docs[i], opts, init);
  37. } catch (error) {
  38. init(error);
  39. }
  40. if (opts.session != null) {
  41. arr[i].$session(opts.session);
  42. }
  43. }
  44. }