Mongoose - How to create a common method for all models?
I have a generic method that I need to implement for all models. Right now I am doing this for each model:
var Product = module.exports = mongoose.model('Product', ProductSchema);
module.exports.flush = function (filename, cb) {
"use strict";
var collection = require(filename);
// todo: reimplement with promises
this.remove({}, function (err) {
if (err) {
console.log(err);
}
else {
this.create(collection, cb);
}
}.bind(this));
};
How can I add this method once so that it exists for all models?
+3
source to share
1 answer
Just define your function for Model
:
var mongoose = require('mongoose');
mongoose.Model.flush = function (filename, cb) {
"use strict";
var collection = require(filename);
// todo: reimplement with promises
this.remove({}, function (err) {
if (err) {
console.log(err);
}
else {
this.create(collection, cb);
}
}.bind(this));
};
Then all the models you create inherit the function flush
:
var Product = module.exports = mongoose.model('Product', ProductSchema);
Product.flush();
+3
source to share