Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cant access findOneAndUpdate in Mongoose using a plugin override?

I'm trying to override the findOneAndUpdate method using a plugin by doing this:

// Messages is a Mongoose Model
await Messages.newFindOneAndUpdate(query, payload, options);

In the Message schema definition I have:

MessagesSchema.plugin(require('../util/schema-api-aware-plugin'));

And that plugin just declares the static method newFindOneAndUpdate:

module.exports = (schema) => {

    schema.statics.newFindOneAndUpdate = async (query, data, options) => {
        const me = this;

        try {
            return await me.findOneAndUpdate(query, data, options);
        }
        catch (err) {
            errorManager(err, res);
            return null;
        }
    }

};

When I run that, I get a type error me.findOneAndUpdate is not a function. The model works, the plugin is attached as it should, the static method is present but for some reason, me which is supposed to be this does not have the method findOneAndUpdate, what am I missing?

like image 482
DomingoSL Avatar asked Dec 05 '25 22:12

DomingoSL


1 Answers

Don't use arrow functions.

Mongoose extensions (like plugins and instance methods) depend on Mongoose being able to set this, which is not supported for arrow functions.

The Mongoose documentation states:

Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.

like image 59
robertklep Avatar answered Dec 08 '25 14:12

robertklep