javascriptmongooseecmascript-6mongoose-schemamongoose-plugins

Mongoose global plugins not working (ES6)


I'm running into an issue with mongoose.plugin() and none of global plugin changes seem to be affecting the schemas.

Other than importing, I've tried directly writing the plugin in the same index.js file, and removing pointer functions. The global plugins just don't seem to be taking effect. I'm just trying to apply toJSON: { virtuals: true } to all models.

"mongoose": "^6.0.12"
import test from './plugins/test.js'
...

// Plugins
mongoose.plugin(test)
...

// Models
import './user.js'
...

test.js content:

export default (schema) => {
  schema.set('toJSON', { ...schema.get('toJSON'), virtuals: true })

  return schema
}

When I directly apply { toJSON: { virtuals: true } } to the user schema it works as intended, but I want to apply this and potentially other plugins to all the models.

Any help or information is appreciated!


Solution

  • I got it working by up splitting plugins and models into separate files and created an index.js for importing all the plugins.

    Within the app.js now I import plugins first followed by the models:

    ...
    import mongoose from 'mongoose'
    import './models/plugins'
    import './models
    ...