skip to Main Content

when I hit the delete method in postman I need to disable the data in MongoDB instead of completely delete. how to do that?

 router.delete("/admin/delete_profile/:id", async (req, res) => {
  try {
    await SomeModel.findByIdAndDelete(req.params.id.trim());
    return send(res, RESPONSE.SUCCESS);
  } catch (err) {
   // res.status(404).send(err.message);
    return send(res, RESPONSE.UNKNOWN_ERROR);
  }
});

schema.js

const { json } = require("body-parser");
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const SomeModelSchema = new Schema({
  first_name: {
    type: String,
    required: true,
  },

  last_name: {
    type: String,
    required: true,
  },

  image: {
    data: Buffer,
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("SomeModel", SomeModelSchema);

2

Answers


  1. You can keep a key like isActive:true in your database for soft delete purpose.When you hit delete api you can simply change this key to false.In this way you can differentiate this document from others and when you want list you can check for documents with isActive:true in your query.

    Login or Signup to reply.
  2. Actually, the approach suggested by @PawanYadav is a good one in my opinion.
    Declare a Boolean flag isActive in your Schema (default to true):

    const SomeModelSchema = new Schema({
      first_name: {
        type: String,
        required: true,
      },
      last_name: {
        type: String,
        required: true,
      },
      image: {
        data: Buffer,
        type: String,
        required: true,
      },
      isActive: {
        type: Boolean,
        default: true,
      }
    });
    

    And use findByIdAndUpdate to set the flag to false to disable the data:

    try {
        await SomeModel.findByIdAndUpdate(req.params.id.trim(), {
          isActive: false,
        });
        return send(res, RESPONSE.SUCCESS);
      } catch (err) {
        // res.status(404).send(err.message);
        return send(res, RESPONSE.UNKNOWN_ERROR);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search