【问题标题】:Node js and mongo , pre, post hook middleware are not executed on findByIdAndUpdateNode js 和 mongo , pre, post hook 中间件不在 findByIdAndUpdate 上执行
【发布时间】:2021-08-13 11:21:01
【问题描述】:

我有一个名为 vehicle 的模式,我可以在其中添加来自管理员的数据,也可以添加导入 csv 文件的数据。顺便说一句,我正在使用keystone js。

现在,当我从管理员添加数据时,钩子被触发并命中,但是当我从导入 csv 文件代码中添加数据时,尽管数据已添加到数据库,但钩子并未被命中和触发

我们可以使用 Vehicle.model.findOneAndUpdat 触发预保存挂钩吗?

我的导入 csv 代码 sn-p

exports.import = function (req, res) {

    let file = fs.createReadStream(req.files.file.path)


    Papa.parse(file, {
        header: true,
        worker: true,
        preview: prev_val,

        complete: function (results) {

            let vehicles = _.each(results.data, function (value, key) {


                let condition = { VIN: value.VIN }

                Vehicle.model.findOneAndUpdate(condition, value, { upsert: true, new: true }, function (err, doc) {



                    }

管理界面

当我从这里添加数据时,钩子被触发并触发

挂钩

  schema.pre('save', function (next) {
    console.log("HIT" , hit)
    if (this.isNew) {
      next()
    } else {
      console.log("this._original" , this._original)
      console.log("this._original1" , this)
      this._diff = getDiff(this, this._original)
      next()
    }
  })

【问题讨论】:

    标签: javascript node.js mongodb mongoose keystonejs


    【解决方案1】:

    来自官方documentation

    此函数触发以下中间件。 findOneAndUpdate()

    所以,它不会触发 pre('save') 中间件。相反,您应该使用 pre('findOneAndUpdate') 中间件。相关官方文档here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 2013-05-13
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多