Mongoose——如何在“init”事件中使用模式中间件?

时间:2021-07-22 19:31:35

It is suggested in the Mongoose docs that I should be able to control the flow using middleware that plugs in to the "init" hook.

Mongoose文档建议我应该能够使用插入到“init”钩子的中间件来控制流。

However, I have so far had success only with "save" and "validate".

然而,到目前为止,我只在“保存”和“验证”上取得了成功。

When I do something like this, neither of these middleware ever get called:

当我做这样的事情时,这些中间件都不会被调用:

MySchema.post( "init", function (next) { console.log("post init") });
MySchema.pre( "init", function (next) { console.log("pre init") });

Am I missing something?

我遗漏了什么东西?

2 个解决方案

#1


22  

It turns out that the "init" event/hook is not fired when creating a new Model, it is only fired, when loading an existing model from the database. It seems that I should use the pre/validate hook instead.

事实证明,“init”事件/钩子在创建新模型时不会被触发,只有在从数据库加载现有模型时才会被触发。看起来我应该使用pre/validate hook。

#2


2  

I have successfully used middleware like MySchema.post('init', function() { ... }); with Mongoose which is then executed for each model instance loaded in a find query. Note that there isn't a next parameter to call with this middleware, it should just return when done.

我已经成功地使用了像MySchema这样的中间件。文章(“init”,函数(){…});使用Mongoose,然后对在find查询中加载的每个模型实例执行。注意,没有下一个要调用的参数与此中间件,它应该只在完成时返回。

#1


22  

It turns out that the "init" event/hook is not fired when creating a new Model, it is only fired, when loading an existing model from the database. It seems that I should use the pre/validate hook instead.

事实证明,“init”事件/钩子在创建新模型时不会被触发,只有在从数据库加载现有模型时才会被触发。看起来我应该使用pre/validate hook。

#2


2  

I have successfully used middleware like MySchema.post('init', function() { ... }); with Mongoose which is then executed for each model instance loaded in a find query. Note that there isn't a next parameter to call with this middleware, it should just return when done.

我已经成功地使用了像MySchema这样的中间件。文章(“init”,函数(){…});使用Mongoose,然后对在find查询中加载的每个模型实例执行。注意,没有下一个要调用的参数与此中间件,它应该只在完成时返回。