Query.prototype.error()

Parameters
  • err «Error|null» if set, exec() will fail fast before sending the query to MongoDB
Returns:
  • «Query» this

Gets/sets the error flag on this query. If this flag is not null or undefined, the exec() promise will reject without executing.

Example:

  1. Query().error(); // Get current error value
  2. Query().error(null); // Unset the current error
  3. Query().error(new Error('test')); // `exec()` will resolve with test
  4. Schema.pre('find', function() {
  5. if (!this.getQuery().userId) {
  6. this.error(new Error('Not allowed to query without setting userId'));
  7. }
  8. });

Note that query casting runs after hooks, so cast errors will override custom errors.

Example:

  1. const TestSchema = new Schema({ num: Number });
  2. const TestModel = db.model('Test', TestSchema);
  3. TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
  4. // `error` will be a cast error because `num` failed to cast
  5. });