Skip to content

Instantly share code, notes, and snippets.

@c0d0g3n
Created May 2, 2017 18:20
Show Gist options
  • Save c0d0g3n/ba2df311ea76963a066874b5183d1624 to your computer and use it in GitHub Desktop.
Save c0d0g3n/ba2df311ea76963a066874b5183d1624 to your computer and use it in GitHub Desktop.
Bug: Mongoose pre validate sub doc middleware Unhandled Rejection
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)
})
{
"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