I have a schema Foo which has pre and post save hooks.
For a special debugging application I'm writing, I grab all the active Foo objects. Then, save them as a subdocument as part of a History schema.
When I save it as part of the subdocument, I do not want my pre/post save hooks to execute.
What's the best way to handle this?
I'd like to avoid having to extract all the data from the Foo object then saving in an new non-mongoose object.
Mongoose middleware are functions that can intercept the process of the init , validate , save , and remove instance methods. Middleware are executed at the instance level and have two types: pre middleware and post middleware.
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. The hooks are specified on RxCollection-level and help to create a clear what-happens-when-structure of your code. Hooks can be defined to run parallel or as series one after another.
Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.
You can define a field to your Foo object like hookEnabled
and you can check it in your hook function. Let me give you an example;
Foo = new Schema({
...
hookEnabled:{
type: Boolean,
required: false,
default: true
}
...
});
And in your hook;
Foo.pre('save', function(next){
self = this
if (self.hookEnabled) {
// dou your job here
next();
} else {
// do nothing
next();
}
});
Before calling save function, you can set hookEnabled field as false like,
var fooModel = new Foo();
fooModel.hookEnabled = false;
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With