Mongoose - adding a global method to all models

Simple question:

How to add static methods to my models in Mongoose that apply to each model, and not just one?

+5
source share
1 answer

So, you have one static method, which (for example, all of your user models, blogs, comments and alerts all share without any differences in implementation?

The actual way to apply behavior to several different models in Mongoose is through plugins, and you can make a global plugin. I follow the traditional syntax, but if you want to use ES6 import and export, feel free to.

// ./models/plugins/echo.js module.exports = function echoPlugin(schema, options) { schema.statics.echo = function(){ console.log('Echo'); } } 

Defines a plugin that can be applied to a single circuit:

 userSchema.plugin(require('./plugins/echo')); 

Or, alternatively, for all models in your project:

 // somewhere in your app startup code var mongoose = require('mongoose'); var echoPlugin = require('./models/plugins/echo'); mongoose.plugin(echoPlugin); 
+6
source

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


All Articles