【问题标题】:Hook to a specific Mongoose model query挂钩到特定的 Mongoose 模型查询
【发布时间】:2015-10-16 04:06:21
【问题描述】:

我在 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();
   });

};

我做错了什么?我想把钩子分开,这样我就可以调用很多不同的模型。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    所以把registerHooks改成:

    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.query。对于多个模型,它会导致循环引用
    • 当我尝试挂钩预查询时,它没有触发。我正在使用 Invoice.find({}).exec()... 调用模型
    • @UmaMaheshwaraa 没有'query' 挂钩,只有'find''findOne'。此外,查询对象作为this 而不是参数传递给钩子回调。查看更新的答案。
    • 感谢您的反馈。我想通了。但我需要在模型级别挂钩它,因为我需要知道查找的“预”挂钩上另一个函数的模型名称。使用架构我不能这样做。 link如果有解决办法请帮忙
    • @JohnnyHK 创建模型后是否可以创建新的钩子?在文档的其他地方使用 mongoose.model ('MyModel')。架构
    猜你喜欢
    • 1970-01-01
    • 2021-04-30
    • 2017-04-18
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2016-10-03
    相关资源
    最近更新 更多