Query.prototype.toConstructor()

Returns:
  • «Query» subclass-of-Query

Converts this query to a customized, reusable query constructor with all arguments and options retained.

Example

  1. // Create a query for adventure movies and read from the primary
  2. // node in the replica-set unless it is down, in which case we'll
  3. // read from a secondary node.
  4. const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
  5. // create a custom Query constructor based off these settings
  6. const Adventure = query.toConstructor();
  7. // Adventure is now a subclass of mongoose.Query and works the same way but with the
  8. // default query parameters and options set.
  9. Adventure().exec(callback)
  10. // further narrow down our query results while still using the previous settings
  11. Adventure().where({ name: /^Life/ }).exec(callback);
  12. // since Adventure is a stand-alone constructor we can also add our own
  13. // helper methods and getters without impacting global queries
  14. Adventure.prototype.startsWith = function (prefix) {
  15. this.where({ name: new RegExp('^' + prefix) })
  16. return this;
  17. }
  18. Object.defineProperty(Adventure.prototype, 'highlyRated', {
  19. get: function () {
  20. this.where({ rating: { $gt: 4.5 }});
  21. return this;
  22. }
  23. })
  24. Adventure().highlyRated.startsWith('Life').exec(callback)