skip to Main Content

I have created a controller that in order to delete records of my Sequelize Model, but right now I am having a trouble that I do not know how to after you delete a record it must change the
defaultValue. Let me demonstrate my code below.

I have a User Model:

module.exports = (sequelize, Sequelize) => {
  const User = sequelize.define("user", {
    user_id: {
      type: Sequelize.STRING,
      autoIncrement: true,
      primaryKey: true,
    },
    username: {
      type: Sequelize.STRING,
    },
    password: {
      type: Sequelize.STRING,
    },
    full_name: {
      type: Sequelize.STRING,
    },
    email: {
      type: Sequelize.STRING,
    },
    role_id: {
      type: Sequelize.STRING,
    },
    is_active: {
      type: Sequelize.BOOLEAN,
      defaultValue: true
    },
    created_date: {
      type: Sequelize.DATE,
    },
    created_by: {
      type: Sequelize.STRING,
    },
    updated_date: {
      type: Sequelize.DATE,
    },
    updated_by: {
      type: Sequelize.STRING,
    },
  });

  return User;
};

And i have create a delete controller:

// delete user
export async function deleteUser(req, res) {
  try {
    const user = await User.findByIdAndDelete(req.params.user_id);
    if (!user) {
      return res.status(404).send();
    }
    res.send(user);
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Server error. Please try again.",
      error: error.message,
    });
  }
}

Now I want to know that how to change the defaultValue of is_active into 0 after delete.

2

Answers


  1. Chosen as BEST ANSWER

    Always do by yourself. Haizzz

    // delete user
    export async function deleteUser(req, res) {
      const id = req.params.user_id;
      try {
        const user_id = await User.findById(id);
        const is_active = await User.update({ is_active: 0 });
        res.status(200).json({
          user_id,
          is_active,
          success: true,
          message: "User is deleted succesfully",
          data: null,
        });
      } catch (error) {
        console.log(error);
        res.status(500).json({
          success: false,
          message: "Server error. Please try again.",
          error: error.message,
          data: null,
        });
      }
    }
    

  2. Looks like you only want to change the is_active as I understand. So, I will suggest you to use findByIdAndUpdate query and set the is_active to 0.

    Code Example

    let doc = await User.findByIdAndUpdate(id,{$set: {is_active: 0}});
    if(!doc) {
    throw new Error('Deletion failed');
    }
    doc = await User.findById(id); // it will retrieve the updated result;
    res.json(doc.toJSON());
    

    Note: This process won’t delete the user from database. So, while validating/verifying the user, also check the is_active field.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search