How to change default value after delete with Sequelize Model and NodeJS?

Viewed 28

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.

1 Answers

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.

Related