After creating the hook

Say I have a mongoose model m.

This model mwas created using a scheme sthat adds a method to register things:

s.methods.log = function(s) {
  this.theLogger(s);
}

theLogger should be served at any time, so I feed theLogger as fast as possible.

It works:

const x = await m.findOne({_id: ...});
x.log("something");

The problem is that this will not work:

const x = new m();
x.log("something"); // <--- theLogger is not defined. 

Is it possible to catch the moment xwith the help of the operator new?

+4
source share
1 answer

I still don't know if these hooks exist, so I finally solved this by expanding the model with a function:

return ((parent) => {
    function HookedModel(a, b) {
        // Pre new hooks here <-----
        this.constructor = parent;
        parent.call(this, a, b);
        // Post new  hooks here <-----
    }
    // Copy all static functions:
    for (const k in parent) {
        if (parent.hasOwnProperty(k)) {
            HookedModel[k] = parent[k];
        }
    }
    HookedModel.__proto__ = parent.__proto__;
    HookedModel.prototype = Object.create(parent.prototype);
    HookedModel.prototype.constructor = HookedModel;
    return HookedModel;
})(model);
+2
source

Source: https://habr.com/ru/post/1685798/


All Articles