This is a simple, easy-to-understand soft deleting package for MongoDB using Mongoose ODM. This package gives you all functionality to soft delete any Mongodb document. So let's start soft deleting...
npm install soft-deleting-mongoose
Firstly import MongooseSchema and create a schema.
const userSchema = new MongooseSchema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
},
role: {
type: String,
default: "user"
},
password: String
});
const User = mongoose.model('User', userSchema);
app.delete("/user/:_id", async (req, res, next) => {
try {
const _id = req.params._id;
const user = await User.softDeleteById(_id);
return res.status(200).json({ success: true, data: user });
} catch (error) {
next(error);
}
});
- .notDeleted()
- .onlyDeleted()
- .withDeleted()
- Model.softDelete(query)
- Model.softDeleteById(_id)
- Model.restoreById(_id)
- Model.restore(query)
- Model.restoreAll()
- Model.forceDeleteById(_id)
- Model.forceDelete(query)
In the above, I have declared a model named User. Now I am giving examples using the User model.
- Get not deleted documents
User.find({}).notDeleted();
- Get only deleted documents
User.find({}).onlyDeleted();
- Get both types of documents (deleted + not deleted)
User.find({}).withDeleted();
In the above, I have declared a model named User. Now I am giving examples using the User model.
- Soft delete the matched documents by query
User.softDelete({ role: "user" });
- Soft delete the document by _id
const _id = "6405d153a208cbfd7b88b0c5";
User.softDeleteById(_id);
- Restore the deleted document by _id
const _id = "6405d153a208cbfd7b88b0c5";
User.restoreById(_id);
- Restore the matched deleted documents by query
const _id = "6405d153a208cbfd7b88b0c5";
User.restoreById(_id);
- Restore all deleted documents
User.restoreAll();
- Permanently delete a document by _id
const _id = "6405d153a208cbfd7b88b0c5";
User.forceDeleteById(_id);
- Permanently delete the matched documents by query
User.forceDeleteById({ role: "sub-admin" });
const User = mongoose.model<IUserDoc, Model<IUserDoc, IQueryHelpers<IUserDoc>>>('User', userSchema);
Heder, IUserDoc is the interface of user, Model is imported from mongoose, and IQueryHelpers is imported from soft-deleting-mongoose package.