What is the best way to hook to existing mongoose.model

不问归期 提交于 2019-12-11 11:03:43

问题


I have a project with multiple self contained mongoose model files. I have another modelprovider which uses the model name and the request to perform an operation. I want to hook the operation to the pre of 'find'

model file

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

I know the hooks to find and findOne works only at the schema level but i want to be done at the model level.

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

I know the documentation proposes to do the pre and post at the schema level but is there any way to use the hooks library or the hooker library to solve this problem.

The reason i want to keep it at the model level is I need to access the model name at the 'find' pre hook. If there is a way to do so then it will be awesome

来源:https://stackoverflow.com/questions/31633286/what-is-the-best-way-to-hook-to-existing-mongoose-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!