Created
June 1, 2018 20:24
-
-
Save readysetmark/78d984a879021b281aa8512ae8bcbd23 to your computer and use it in GitHub Desktop.
Mongoose pre-validation hook
This file contains 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
"use strict"; | |
const mongoose = require('mongoose'); | |
const thingWithNameSchema = mongoose.Schema({ | |
name: String, | |
}); | |
thingWithNameSchema.pre('validate', (next) => { | |
console.log(this); | |
console.log(this.name); | |
next(); | |
}); | |
const ThingWithName = mongoose.model('ThingWithName', thingWithNameSchema); | |
const thing = new ThingWithName({ name: 'Namers namer name name' }); | |
thing.validate() | |
.then(() => console.log('done')) | |
.catch(() => console.log('error')); | |
// Output: | |
// {} | |
// undefined | |
// done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solution: Don't use an arrow function, use
function (next)
instead. Arrow functions don't have their ownthis
.