如何在nodejs中使用hooks/sequelize更新数据库

how to update Database using hooks/sequelize in nodejs

这是我的model.js


var methods = require("../hooks");

module.exports = (sequelize, DataTypes) => {
  const Users = sequelize.define(
    "dummytables",
    {
      first_name: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: "First Name",
      },
      last_name: {
        type: DataTypes.STRING,
        allowNull: false,
        defaultValue: "Last Name",
      },
      full_name: {
        type: DataTypes.STRING,
        allowNull: true,
      },
    },
    {
      hooks: methods.hooks,
    }
  );
  return Users;

这是我的 hooks.js 文件

const dummytable = require("../models/model");

var hooks = {};

exports.hooks = hooks;

var set_full_name = (dummytable) => {
  dummytable.full_name = dummytable.first_name + ` ` + dummytable.last_name;
};

hooks.beforeCreate = [set_full_name];
hooks.beforeUpdate = [set_full_name];

这是我的 apiRoutes.js 文件

const express = require("express");
const router = express.Router();
const db = require("../models");


// update data
router.put("/", (req, res) => {
  const { first_name, last_name, id } = req.body;
  db.dummytables
    .update(
      {
        first_name,
        last_name,
      },
      {
        where: {
          id,
        },
      }
    )
    .then(() => res.send("success"));
});

我想使用 hooks

插入和更新 full_name

当我插入任何数据时 full_name 从 first_name & last_name 获取值但是 当我尝试更新数据时,它没有更新 full_name

我不知道如何使用挂钩更新 full_name

调用update时需要使用individualHooks

// update data
router.put("/", (req, res) => {
  const { first_name, last_name, id } = req.body;
  db.dummytables
    .update(
      {
        first_name,
        last_name,
      },
      {
        where: {
          id,
        },
        individualHooks: true
      }
    )
    .then(() => res.send("success"));
});