我有一个包含多个自包含的mongoose模型文件的项目。我有另一个modelprovider,它使用模型名称和请求来执行操作。我想将操作挂钩到'find'的前面
模型文件
'use strict';
// load the things we need
var mongoose = require('mongoose');
var config = require('../../config/environment');
var auth_filter = require('../../auth/acl/lib/queryhook');
var modelProviders = require('../../auth/acl/lib/modelprovider');
var invoice_db = mongoose.createConnection(config.mongo.url + '/invoiceDB'); //connect to buyer DB
var path = require('path');
// define the schema for our invoice details model
var invoicedetailSchema = new Schema({
//SCHEMA INFO
});
var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);
//REGISTER THE HOOKS TO THE MDOEL
auth_filter.registerHooks(InvoiceModel);
promise.promisifyAll(InvoiceModel);
promise.promisifyAll(InvoiceModel.prototype);
module.exports = InvoiceModel;
modelProviders().setModel(InvoiceModel.modelName, path.resolve(__dirname, __filename) );
我知道查找的钩子和findOne只能在模式级别工作,但我想在模型级别完成。
registerhooks
'use strict';
var hooks = require('hooks'),
_ = require('lodash');
var mongoose = require('mongoose');
exports.registerHooks = function( model) {
var Qry = mongoose.Query;
var query = model.find();
var Sch = mongoose.Schema;
var schema = model.schema
_.assign(model, hooks);
model.hook('find', mongoose.model.prototype.find)
model.pre('find', function(next){
console.log('hell')
return next()
})
console.log(model)
};
exports.registerHooks_ = function( model) {
var Qry = mongoose.Query;
var query = model.find();
var Sch = mongoose.Schema;
var schema = model.schema
_.assign(schema, hooks);
schema.hook('find', query)
schema.pre('find', function(next){
console.log('hell')
return next()
})
console.log(schema)
};
我知道文档建议在架构级别进行前置和后置,但有没有办法使用钩子库或钩子库来解决这个问题。
我想将它保持在模型级别的原因是我需要在'find'预钩子上访问模型名称。如果有办法这样做,那就太棒了