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
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 withisActive:true
in your query.Actually, the approach suggested by @PawanYadav is a good one in my opinion.
Declare a
Boolean
flagisActive
in your Schema (default totrue
):And use
findByIdAndUpdate
to set the flag tofalse
to disable the data: