Query.prototype.orFail()

Parameters
  • [err] «Function|Error» optional error to throw if no docs match filter. If not specified, orFail() will throw a DocumentNotFoundError
Returns:
  • «Query» this

Make this query throw an error if no documents match the given filter. This is handy for integrating with async/await, because orFail() saves you an extra if statement to check if no document was found.

Example:

  1. // Throws if no doc returned
  2. await Model.findOne({ foo: 'bar' }).orFail();
  3. // Throws if no document was updated
  4. await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
  5. // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
  6. await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
  7. // Throws "Not found" error if no document was found
  8. await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
  9. orFail(() => Error('Not found'));