3

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?

DomingoSL
  • 14,920
  • 24
  • 99
  • 173

1 Answers1

3

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381