node.js - Mongoose - 如何为所有模型创建通用方法?

标签 node.js mongoose

我有一个需要为所有模型实现的通用方法。现在我对每个模型都这样做:

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));
};

我怎样才能一次添加这个方法,以便它存在于所有模型中?

最佳答案

只需为 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));
};

那么你创建的所有模型都会继承flush函数:

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

关于node.js - Mongoose - 如何为所有模型创建通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428001/

相关文章:

node.js - Express 和异步/等待 : shall I wrap the lot with try/catch?

node.js - Alexa 在播放时不接受音频命令

node.js - 这个错误是什么意思? "DeprecationWarning: OutgoingMessage.prototype._headers is deprecated"以及如何在 nodejs12 中复制它

node.js - Heroku+Node.js 如何克隆node_modules?

javascript - Mongoose :复制查询结果

node.js - 如何在mongoose中编写动态查询

javascript - 从 API Node JS 获取不正确的数据

node.js - mongoose find 不返回任何文档,而 compass 则返回

mongodb - 从 mongo 返回数据表的正确方法

node.js - Node.js 如何处理未关闭的 HTTP 响应