Search code examples
javascriptnode.jsmongodbmongoosekeystonejs

Node js and mongo , pre, post hook middleware are not executed on findByIdAndUpdate


I have a schema named vehicle where I can add data from the admin and also I can add data importing a csv file. I am using keystone js by the way.

Now when i add data from the admin the hook is triggered and hit but when I add data from my import csv file code the hook is not hit and triggered although the data is added to the database

can we trigger the pre save hook using Vehicle.model.findOneAndUpdat ?

my importing csv code snippet

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) {



                    }

Admin UI

When i add data from here the hook is hit anf triggered my admin -

Hook

  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()
    }
  })

Solution

  • From official documentation:

    This function triggers the following middleware. findOneAndUpdate()

    So, it won't trigger pre('save') middleware. Instead you should use pre('findOneAndUpdate') middleware. Related official doc here.