Mongoose - How to create a common method for all models?

时间:2015-05-24 20:28:04

标签: node.js mongoose

I have a common method I need to implement for all models. Right now I do it 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 it existed for all models?

1 个答案:

答案 0 :(得分:3)

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 your created models will inherit the flush function:

var Product = module.exports = mongoose.model('Product', ProductSchema);
Product.flush();