queryhelpers.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*!
  2. * Module dependencies
  3. */
  4. var utils = require('./utils')
  5. /*!
  6. * Prepare a set of path options for query population.
  7. *
  8. * @param {Query} query
  9. * @param {Object} options
  10. * @return {Array}
  11. */
  12. exports.preparePopulationOptions = function preparePopulationOptions (query, options) {
  13. var pop = utils.object.vals(query.options.populate);
  14. // lean options should trickle through all queries
  15. if (options.lean) pop.forEach(makeLean);
  16. return pop;
  17. }
  18. /*!
  19. * Prepare a set of path options for query population. This is the MongooseQuery
  20. * version
  21. *
  22. * @param {Query} query
  23. * @param {Object} options
  24. * @return {Array}
  25. */
  26. exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ (query, options) {
  27. var pop = utils.object.vals(query._mongooseOptions.populate);
  28. // lean options should trickle through all queries
  29. if (options.lean) pop.forEach(makeLean);
  30. return pop;
  31. }
  32. /*!
  33. * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise,
  34. * it returns an instance of the given model.
  35. *
  36. * @param {Model} model
  37. * @param {Object} doc
  38. * @param {Object} fields
  39. *
  40. * @return {Model}
  41. */
  42. exports.createModel = function createModel(model, doc, fields) {
  43. var discriminatorMapping = model.schema
  44. ? model.schema.discriminatorMapping
  45. : null;
  46. var key = discriminatorMapping && discriminatorMapping.isRoot
  47. ? discriminatorMapping.key
  48. : null;
  49. if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) {
  50. return new model.discriminators[doc[key]](undefined, fields, true);
  51. }
  52. return new model(undefined, fields, true);
  53. }
  54. /*!
  55. * Set each path query option to lean
  56. *
  57. * @param {Object} option
  58. */
  59. function makeLean (option) {
  60. option.options || (option.options = {});
  61. option.options.lean = true;
  62. }