钩住特定的Mongoose模型查询

我在invoice.js中有自包含的模型

'use strict'; // load the things we need var mongoose = require('mongoose'); var auth_filter = require('../../auth/acl/lib/queryhook'); var invoice_db = mongoose.createConnection(config.mongo.url + '/invoiceDB'); // PROMISE LIBRARY USED FOR ASYNC FLOW var promise = require("bluebird"); var Schema = mongoose.Schema, ObjectId = Schema.Types.ObjectId; // define the schema for our invoice details model var invoicedetailSchema = new Schema({ //SCHEMA INFO }); var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema); // create the model for seller and expose it to our app auth_filter.registerHooks(InvoiceModel); module.exports = InvoiceModel; 

我想钩住这个模型的预查询。 我正在尝试使用钩子来完成,但是我没有成功。 我正在注册使用auth_filter文件的钩子如下

 'use strict'; var hooks = require('hooks'), _ = require('lodash'); exports.registerHooks = function (model) { model.pre('find', function(next,query) { console.log('test find'); next(); }); model.pre('query', function(next,query) { console.log('test query'); next(); }); }; 

我究竟做错了什么? 我想保持钩子分开,以便我可以调用很多不同的模型。

查询钩子需要在模式上定义,而不是模型。 此外,没有'query'钩子, query对象被传递给钩子callback,而不是作为参数。

所以把registerHooks改为:

 exports.registerHooks = function (schema) { schema.pre('find', function(next) { var query = this; console.log('test find'); next(); }); }; 

然后在创build模型之前用模式调用它:

 var invoicedetailSchema = new Schema({ //SCHEMA INFO }); auth_filter.registerHooks(invoicedetailSchema); var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);