gpt4 book ai didi

node.js - Hook 到特定的 Mongoose 模型查询

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:43 25 4
gpt4 key购买 nike

我在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;

我想 Hook 该模型的预查询。我正在尝试使用钩子(Hook)来实现这一点,但我没有成功。我正在使用 auth_filter 文件注册钩子(Hook),如下所示

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

};

我做错了什么?我想将钩子(Hook)分开,以便我可以调用许多不同的模型。

最佳答案

查询hooks需要在架构上定义,而不是在模型上定义。此外,没有 'query' 钩子(Hook),并且 query 对象作为 this 而不是作为参数传递给钩子(Hook)回调。

因此将 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);

关于node.js - Hook 到特定的 Mongoose 模型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31628230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com