Disabling a plugin in Mongoose schema

Viewed 378

I'm using a Mongoose plugin (mongoose-patch-history) which automatically tracks changes to a model to a MongoDB collection. I need to selectively disable the plugin (i.e. I only want to track changes on certain models, and not others, based on a flag/critera). I believe that I need some kind of filtering capability within the plugin, but it doesn't provide a mechanism for this. Is there any other way I can achieve this?

1 Answers

Plugins set middlewares on the schema. In my case, the plugin timestamp registered this middleware

schema.pre('findOneAndUpdate', function (next) {
    if (this.op === 'findOneAndUpdate') {
        this._update = this._update || {};
        this._update[updatedAt] = new Date;
        this._update['$setOnInsert'] = this._update['$setOnInsert'] || {};
        this._update['$setOnInsert'][createdAt] = new Date;
    }
});

I couldn't manage to delete this middleware from the schema (here is an answer on how to access middlewares registered).

SOLUTION

I created a new instance of the Schema with the exact same SchemaType. I avoided then adding the plugin.

To create a schema with the same schemaType, just access the property paths

import _ from 'lodash'
import mongoose from 'mongoose'
// schema with plugin
import EntitySchema from '../entity.model'

// creating clone of paths for cleanliness
const schemaType = _.cloneDeep(EntitySchema.paths)

// new schema, free of plugins
const newSchema = new mongoose.Schema(schemaType)
Related