Created
May 2, 2017 18:20
-
-
Save c0d0g3n/ba2df311ea76963a066874b5183d1624 to your computer and use it in GitHub Desktop.
Bug: Mongoose pre validate sub doc middleware Unhandled Rejection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let mongoose = require('mongoose') | |
let Promise = require('bluebird') | |
mongoose.Promise = Promise | |
mongoose.connect("mongodb://localhost/bug") | |
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) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "bug-report2", | |
"version": "1.0.0", | |
"description": "", | |
"main": "bug.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"bluebird": "^3.5.0", | |
"mongoose": "^4.9.7" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment