find_one.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const handleCallback = require('../utils').handleCallback;
  3. const OperationBase = require('./operation').OperationBase;
  4. const toError = require('../utils').toError;
  5. const Aspect = require('./operation').Aspect;
  6. const defineAspects = require('./operation').defineAspects;
  7. class FindOneOperation extends OperationBase {
  8. constructor(collection, query, options) {
  9. super(options);
  10. this.collection = collection;
  11. this.query = query;
  12. }
  13. execute(callback) {
  14. const coll = this.collection;
  15. const query = this.query;
  16. const options = this.options;
  17. try {
  18. const cursor = coll
  19. .find(query, options)
  20. .limit(-1)
  21. .batchSize(1);
  22. // Return the item
  23. cursor.next((err, item) => {
  24. if (err != null) return handleCallback(callback, toError(err), null);
  25. handleCallback(callback, null, item);
  26. });
  27. } catch (e) {
  28. callback(e);
  29. }
  30. }
  31. }
  32. defineAspects(FindOneOperation, [Aspect.EXPLAINABLE]);
  33. module.exports = FindOneOperation;