我有一个需要为所有模型实现的通用方法。现在我对每个模型都这样做:
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/