Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - add global method to all models

Simple question:

How can I add static methods to my models in Mongoose, that applies to every model instead of just one?

like image 779
Alex Wohlbruck Avatar asked Nov 30 '16 01:11

Alex Wohlbruck


1 Answers

So you have one static method that (eg) your User, Blog, Comment, and Alert models all share without any differences in implementation?

The de facto way to apply behavior to multiple different models in Mongoose is through plugins, and you can do a global plugin. I'll stick to traditional syntax, but if you want to use ES6 imports and exports feel free.

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

That defines a plugin which could be applied to a single schema like so:

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

Or alternatively to all models in your project like so:

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

mongoose.plugin(echoPlugin);
like image 79
Paul Avatar answered Nov 15 '22 22:11

Paul