completeMany.js 1.2 KB

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