Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 钩住特定的Mongoose模型查询_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 钩住特定的Mongoose模型查询

Node.js 钩住特定的Mongoose模型查询,node.js,mongodb,mongoose,Node.js,Mongodb,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 LIBR

我在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_过滤器文件注册钩子,如下所示

'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
对象作为
this
而不是作为参数传递给钩子回调

因此,将注册簿更改为:

exports.registerHooks = function (schema) {

    schema.pre('find', function(next) {
          var query = this;
          console.log('test find');
          next();
       });
};
然后在创建模型之前使用模式调用它:

var invoicedetailSchema = new Schema({
    //SCHEMA INFO
});

auth_filter.registerHooks(invoicedetailSchema);

var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);

谢谢你的澄清。这很有效。同时,我研究了一个名为hooks的库,它需要一个查询对象,比如mongoose.query来钩住。有没有办法从mongoose模型中获取查询对象并使用钩子。我发现这样做更有力量。如果只有一个模型,那么实现是简单的,因为我可以钩住mongoose.query。对于多个模型,它会导致循环引用当我尝试钩住预查询时,它不会触发。我使用Invoice.find({}).exec()…@UmaMaheshwaraa调用模型,没有
'query'
钩子,只有
'find'
'findOne'
。此外,查询对象作为
this
而不是参数传递给钩子回调。请参阅更新的答案。感谢您的反馈。我想是的。但是我需要在模型级别钩住它,因为我需要知道find的'pre'钩子中另一个函数的模型名。使用该模式,我无法这样做。如果您有任何解决方案,请帮助