在猫鼬中预先保存中间件 [英] pre save middleware in mongoose
问题描述
我是第一次使用预保存中间件,并在其中有点困惑.
i am first time using pre save middleware and getting a bit confusion in it.
它运行得非常好,即使我没有调用 next() 也正在执行我的保存方法
It runs perfectly fine and also my save method is getting executed eventhough i am not calling the next()
案例 1
tourSchema.pre('save', function () {
console.log('first middleware is getting called');
})
但是当我这样做时,在函数参数中声明了 next 但我没有调用 next() 它挂在那里并且 save 方法没有被执行
But when i do like this when next is declared inside the function params but i don't call the next() it hangs there and the save method is not getting executed
案例 2
tourSchema.pre('save', function (next) {
console.log('first middleware is getting called');
});
但是一旦我调用 next() 它就会被执行
But as soon as i call the next() it gets executed
案例 3
tourSchema.pre('save', function (next) {
console.log('first middleware is getting called');
next()
});
所以我只想知道第二种情况有什么问题.在这方面,我只有这个预中间件.如何在函数参数中定义 next 很重要,save 方法也应该在第二种情况下执行,因为我没有任何第二个 pre 中间件.
so i only want to know what's the wrong with the second case . In this i have only and only this pre middleware . How defining the next inside the function params can matter, the save method should also be executed in the second case since i don't have any second pre middleware.
推荐答案
mongoose 使用 kareem 库来管理钩子.
mongoose uses kareem library to manage hooks.
kareems
使用钩子函数的 length
属性来确定 next
是否被定义为参数.
kareems
makes use of the length
property of your hook function to determine whether next
is defined as an argument or not.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length
你的第一个函数没有参数,kareem
会假设这是一个同步函数
Your first function has no arguments, kareem
will assume this is a sync function
const firstFunction = function () {
console.log('first middleware is getting called');
})
console.log(firstFunction.length) // this will output 0
您的第二个函数有 1 个参数,kareem
库将看到您的函数接受 next
参数.它将传递一个回调并在 next
函数中执行它.由于 next
永远不会被调用,所以永远不会调用该回调.
Your second function has 1 argument, the kareem
library will see your function accept next
arguments. It will pass a callback and execute it in the next
function. Since next
is never called, that callback will be never called.
const secondFunction = function (next) {
console.log('first middleware is getting called');
})
console.log(secondFunction.length) // this will output 1
这篇关于在猫鼬中预先保存中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!