【问题标题】:pre save middleware in mongoose在猫鼬中预先保存中间件
【发布时间】:2020-08-11 11:03:23
【问题描述】:

我是第一次使用预存中间件,有点困惑。

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

案例一

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

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

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

所以我只想知道第二种情况有什么问题。在这我只有而且只有这个预中间件。 如何在函数参数中定义 next 很重要,save 方法也应该在第二种情况下执行,因为我没有任何第二个 pre 中间件。

【问题讨论】:

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


    【解决方案1】:

    mongoose 使用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
    

    【讨论】:

    • 我在答案中添加了更多解释
    【解决方案2】:

    thammada 的回答完美地解释了您的问题,我只想补充说您实际上可以使用异步函数来逃避调用 next() 的义务

    当每个中间件调用下一个时,前中间件函数一个接一个地执行。

    `const schema = new Schema(..);
     schema.pre('save', function(next) {
       // do stuff
       next();
     });`
    

    在 mongoose 5.x 中,您可以使用返回 promise 的函数,而不是手动调用 next()。特别是,您可以使用 async/await。

    schema.pre('save', function() {
      return doStuff().
      then(() => doMoreStuff());
    });
    

    Read more about it here

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 2018-11-29
      • 2021-07-06
      • 2018-03-04
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      相关资源
      最近更新 更多