How to add a "pre" middleware to mongoose model AFTER creating the model

Issue

I need to add a pre mongoose middleware to a model (not schema) after the model was created from the schema.

const mongoose = require('mongoose');
const FooSchema = new mongoose.Schema({
    foo: String
});
const FooModel = mongoose.model('Foo', FooSchema);

And then in the middle of the runtime

 FooModel.schema.pre('save', myMiddleware);

However, after some debugging, I found that all the middewares must be added before creating the model.

Is there a way to add my middleware after model creation?

Solution

There is not such possibility in Mongoose unfortunately.

Answered By – Vasyl Boroviak

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.