Skip to content

Instantly share code, notes, and snippets.

@readysetmark
Created June 1, 2018 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save readysetmark/78d984a879021b281aa8512ae8bcbd23 to your computer and use it in GitHub Desktop.
Save readysetmark/78d984a879021b281aa8512ae8bcbd23 to your computer and use it in GitHub Desktop.
Mongoose pre-validation hook
"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
@readysetmark
Copy link
Author

Solution: Don't use an arrow function, use function (next) instead. Arrow functions don't have their own this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment