Post validate error handler does not fire #4885

Open
sshymko opened this Issue Jan 10, 2017 · 4 comments

Projects

None yet

2 participants

@sshymko
sshymko commented Jan 10, 2017

Environment:

  • Node.js 6.7.0
  • MongoDB 3.2.10
  • Mongoose 4.7.2

Steps to reproduce:

  1. Execute the following test script:
let PaymentSchema = new db.Schema({
  currency: {type: String, required: true, enum: ['USD'], default: 'USD'},
  amount: {type: Number, required: true},
});

PaymentSchema.post('validate', function(error, doc, next) {
  next(new Error('Invalid payment information'));
});

let PaymentModel = db.model('Payment', PaymentSchema);

let payment = new PaymentModel({
  currency: 'EUR',
  amount: 10,
});

payment.validate()
  .catch((error) => {
    console.log(error.message);
  });

let error = payment.validateSync();
if (error) {
  console.log(error.message);
}

Expected result:

  • Post-validate error handler catches & converts all validation errors
  • Model validation methods validate and validateSync return converted error

Actual result:

  • Post-validate error handler does NOT get called upon validation failure
  • Model validation methods return original error
@varunjayaraman
Collaborator

Thanks for the repro script.

Looks like it also doesn't run when you actually make a db operation:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;

const GITHUB_ISSUE = `gh-4885`;

mongoose.connect(`mongodb://localhost:27017/${ GITHUB_ISSUE }`);
let PaymentSchema = new mongoose.Schema({
  currency: { type: String, required: true, enum: ['USD'], default: 'USD' },
  amount: { type: Number, required: true },
});

PaymentSchema.post('validate', function(error, doc, next) {
  console.log(`Error in post validate hook ${error}`)
  next(new Error('Invalid payment information'));
});

let PaymentModel = mongoose.model('Payment', PaymentSchema);

try {
  let payment = new PaymentModel({
    currency: 'EUR',
    amount: 10,
  });

  console.log('saving...');
  payment.save()
    .then(doc => {
      console.log('saved', doc);
      process.exit(0);
    })
    .catch(error => {
      console.error(`Error in catch handler ${error}\n${error.stack}`);
      process.exit(2);
    })

} catch (error) {
  console.error(error);
  process.exit(2);
}

@varunjayaraman varunjayaraman added this to the 4.7.8 milestone Jan 12, 2017
@sshymko
sshymko commented Jan 17, 2017

Looks like post save error handler does not fire either. Do error handlers ever fire at all?

@sshymko
sshymko commented Jan 17, 2017 edited

@varunjayaraman
You confirmed the issue, didn't you? Why has the label changed "confirmed-bug" -> "bug?" than?

@varunjayaraman
Collaborator

yep, sorry about that, not sure what happened

@varunjayaraman varunjayaraman added confirmed-bug and removed bug? labels Jan 17, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment