Reputation: 603
I have self contained model in 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;
I want to hook to the pre query for this model. I am trying to accomplish that using hooks but i am not successful with that. I am registering the hook using auth_filter file as below
'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();
});
};
What am I doing wrong? I want to keep the hooks separate so that I can call for a lot of different models.
Upvotes: 1
Views: 823
Reputation: 311855
Query hooks need to be defined on the schema, not the model. Also, there is no 'query'
hook, and the query
object is passed to the hook callback as this
instead of as a parameter.
So change registerHooks
to be:
exports.registerHooks = function (schema) {
schema.pre('find', function(next) {
var query = this;
console.log('test find');
next();
});
};
And then call it with the schema before creating your model:
var invoicedetailSchema = new Schema({
//SCHEMA INFO
});
auth_filter.registerHooks(invoicedetailSchema);
var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);
Upvotes: 1