2

this is my 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;

this is my hooks.js file

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];

this is my apiRoutes.js file

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"));
});

I want to insert and update full_name by using hooks

when i am inserting any data full_name get the value from first_name & last_name but when i am trying to update the data its not updating full_name

i dont know how to update full_name using hooks

1 Answer 1

2

you need to use individualHooks when calling update

// 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"));
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.