Mongoose: Errors thrown in pre validation middleware of sub doc result in Unhandled Rejection

Created on 2 May 2017  路  2Comments  路  Source: Automattic/mongoose

Errors that are thrown or passed to next() in the pre validation middleware of a sub doc are not propagated correctly to the error handler, but instead get lost somewhere (Unhandled Rejection) (forgive my terminology).

I assume this is a bug as pre save errors get caught correctly, as well as pre save and pre validate errors on regular (no sub doc) docs.

Here is a gist to reproduce the bug.

I'm using Mongoose 4.9.6.

confirmed-bug

All 2 comments

thanks for the repro script, this looks like a bug. I've posted a repro script without bluebird since i was able to repro without it and i'd like to minimize dependencies in the repro script:

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

const GITHUB_ISSUE = `gh-5215`;

mongoose.connect(`mongodb://localhost/${ GITHUB_ISSUE }`);
let db = mongoose.connection; 

db.on('error', (err) => {
    return console.error('Connection error:', err)
})


// child schema
let childSchema = new mongoose.Schema({
    someValue: String
})



// COMMENT OUT MIDDLEWARE TO SEE THE BEHAVIOR OF OTHERS
childSchema.pre('validate', (next) => {
    next(new Error('Error: child pre validate'))
})

childSchema.pre('save', (next) => {
    next(new Error('Error: child pre save'))
})



let Child = mongoose.model('Child', childSchema)


// parent schema
let parentSchema = new mongoose.Schema({
    // NOTE: child model must be created already or its middleware will not trigger at all
    child: childSchema // Child.schema
})



// COMMENT OUT MIDDLEWARE TO SEE THE BEHAVIOR OF OTHERS
parentSchema.pre('validate', (next) => {
    next(new Error('Error: parent pre validate'))
})

parentSchema.pre('save', (next) => {
    next(new Error('Error: parent pre save'))
})



let Parent = mongoose.model('Parent', parentSchema)


// trigger run process where events trigger
let test = new Parent()
test.child = {}
test.child.someValue = "test"

console.log(test)

test.save()
    .then((test) => {
        console.log("Successfully saved!")
    })
    .catch((err) => {
        console.log(err.message)
    });

Issue's been fixed, fix will be released with 4.9.9

Was this page helpful?
0 / 5 - 0 ratings