将中间件预先保存在猫鼬中

时间:2020-04-27 19:09:48

标签: node.js mongoose mongoose-schema mongoose-middleware

我是第一次使用预保存中间件,并且对此有些困惑。

它运行得非常好,即使我没有调用next(),我的save方法也正在执行

案例1

tourSchema.pre('save', function () {
  console.log('first middleware is getting called');
})

但是当我这样做时,在函数参数中声明了next,但我没有调用next()时,它挂在那里并且save方法没有执行

案例2

tourSchema.pre('save', function (next) {
  console.log('first middleware is getting called');
});

但是一旦我调用next(),它就会被执行

案例3

tourSchema.pre('save', function (next) {
  console.log('first middleware is getting called');
  next()
});

所以我只想知道第二种情况出了什么问题。在这种情况下,我只有并且只有这个前置中间件。 在函数params中定义下一个有多重要,在第二种情况下还应该执行save方法,因为我没有任何第二个前置中间件。

1 个答案:

答案 0 :(得分:0)

猫鼬使用kareem库来管理钩子。

kareems利用钩子函数的length属性来确定是否将next定义为自变量。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length

您的第一个函数没有参数,kareem将假定这是一个同步函数

const firstFunction = function () {
  console.log('first middleware is getting called');
})
console.log(firstFunction.length) // this will output 0

您的第二个函数有1个参数,kareem库将看到您的函数接受next个参数。它将传递回调并在next函数中执行。由于从未调用过next,因此将永远不会调用该回调。

const secondFunction = function (next) {
  console.log('first middleware is getting called');
})
console.log(secondFunction.length) // this will output 1