在保存之前挂钩,不触发钩子 [英] sequelize beforeSave hook not firing

查看:83
本文介绍了在保存之前挂钩,不触发钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用sequelize-auto生成了模型,并且需要使用beforeSave挂钩(请参见

I've generated models with sequelize-auto, and need to use a beforeSave hook (see here). The hook isn't firing as far as I can tell. sequelize version ^4.20.1, sequelize-auto version ^0.4.29, express version ~4.15.5. Can anyone help?

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('trad', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    geom: {
      type: DataTypes.GEOMETRY('POINT', 4326),
      allowNull: true
    },
    ...
  }, {
    hooks: {
      beforeSave: (instance, options) => {
        console.log('Saving geom: ' + instance.geom);
        if (instance.geom && !instance.geom.crs) {
          instance.geom.crs = {
            type: 'name',
            properties: {
              name: 'EPSG:4326'
            }
          };
        }
      }
    },
    tableName: 'trad',
    timestamps: false,
  });
};

这是来自PUT请求的代码:

Here's the code from the PUT request:

// Update (PUT)
router.put('/table/:table/:id', function(req, res, next) {
  db.resolveTableName( req )
  .then( table => {
    const primaryKey = table.primaryKeyAttributes[0];
    var where = {};
    where[primaryKey] =  req.params.id;
    console.log('Put - pkey: ' + primaryKey);

    auth.authMethodTable( req )
    .then( function() {
      table.update( req.body, {
        where: where,
        returning: true,
        plain: true
      })
      .then( data => {
        res.status(200).json( data[1].dataValues );
      })
      .catch( function (error ) {
        res.status(500).json( error );
      });
    })
    .catch( function( error ) {
      res.status(401).json('Unauthorized');
    });
  })
  .catch( function(e) {
    res.status(400).json('Bad request');
  });
});

推荐答案

除非指定,否则beforeSave挂钩将针对单个模型实例触发,但不适用于批量更新.就您而言,您可以选择以下两种方式之一:

The beforeSave hook fires for individual model instances, but not for bulk updates unless specified. In your case, you have one of two options:

(1)将individualHooks传递给您的查询:

(1) Pass individualHooks to your query:

table.update( req.body, {
  where: where,
  returning: true,
  individualHooks: true
  plain: true
})

(2)在更新之前获取模型实例:

(2) Fetch the model instance before updating:

table.findById(req.params.id)
  .then(function(instance) {
    instance.update(req.body, {
      returning: true
      plain: true
    })
  })

这篇关于在保存之前挂钩,不触发钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆