1

I'm able to delete data from the view , but at the sametime its getting deleted from mongodb which shouldn't happen.

I tried mongoose-soft-delete plugin to perform soft delete, but it isn't working

//schema

var mongoose= require('mongoose');
let softDelete = require('mongoosejs-soft-delete');
var Schema=mongoose.Schema;
var newblogSchema=new Schema({
    user_id:Number,
    title:String,
    description:String,
    summary:String,
    hashtag:String

})
var newblogs=mongoose.model('NewBlog',newblogSchema);
newblogSchema.plugin(softDelete);
module.exports=newblogs;

//html template

<table>
    <tr>
        <th>Title</th>
        <th>Description</th>
        <th>Summary</th>
        <th>HashTags</th>
    </tr>
   <tr *ngFor="let blog of blogs;">
        <td >{{blog.title}}</td>&nbsp;&nbsp;
        <td [innerHtml]="blog.description| safeHtml">{{blog.description}}</td>&nbsp;&nbsp;&nbsp;
        <td>{{blog.summary}}</td>&nbsp;&nbsp;&nbsp;
        <td>{{blog.hashtag}}</td>&nbsp;&nbsp;&nbsp;

        <td> <a routerLink="/blog"><button type="button" 
        (click)="editblog(blog._id,blog.title,blog.description,blog.summary,blog.hashtag)">
    Edit</button></a>
        <td><button type="button" (click)="deleteblog(blog._id)">Delete</button>   
   </tr>
  </table>

//ts file

deleteblog(blogid) {
    var result = confirm('Want to delete?');
    if (result === true) {
      this.blogservice.deleteblog(blogid).subscribe(response => {this.blogs = response; });

    }

//service

deleteblog(blogid):Observable<any>{
    return Observable.create(observer=>{
      this.http.post('http://localhost:4000/api/deleteblog', {_id: blogid}, {headers: new HttpHeaders({'Content-Type':'application/json'})}
      )
      .subscribe((response:Response)=>{
        observer.next(response);
        observer.complete();
      });
    });

   }

//api.js

router.post('/deleteblog',(req,res)=>{
    var body=req.body;
    newblog.findByIdAndRemove({_id:body._id},(error,newblog)=>{if(error){
        console.log(error);

    }
    else{
        return res.json({message:'deleted',data:newblog});
    }

});
});

Now the data is getting deleted from view as well as mongodb.

Expected result is to delete data only from the view and not from mongodb

3 Answers 3

2

we can implement soft delete with plugin, middleware and $isDeleted document method

soft delete plugin code:

import mongoose from 'mongoose';

export type TWithSoftDeleted = {
  isDeleted: boolean;
  deletedAt: Date | null;
}

type TDocument = TWithSoftDeleted & mongoose.Document;

const softDeletePlugin = (schema: mongoose.Schema) => {
  schema.add({
    isDeleted: {
      type: Boolean,
      required: true,
      default: false,
    },
    deletedAt: {
      type: Date,
      default: null,
    },
  });

  const typesFindQueryMiddleware = [
    'count',
    'find',
    'findOne',
    'findOneAndDelete',
    'findOneAndRemove',
    'findOneAndUpdate',
    'update',
    'updateOne',
    'updateMany',
  ];

  const setDocumentIsDeleted = async (doc: TDocument) => {
    doc.isDeleted = true;
    doc.deletedAt = new Date();
    doc.$isDeleted(true);
    await doc.save();
  };

  const excludeInFindQueriesIsDeleted = async function (
    this: mongoose.Query<TDocument>,
    next: mongoose.HookNextFunction
  ) {
    this.where({ isDeleted: false });
    next();
  };

  const excludeInDeletedInAggregateMiddleware = async function (
    this: mongoose.Aggregate<any>,
    next: mongoose.HookNextFunction
  ) {
    this.pipeline().unshift({ $match: { isDeleted: false } });
    next();
  };

  schema.pre('remove', async function (
    this: TDocument,
    next: mongoose.HookNextFunction
  ) {
    await setDocumentIsDeleted(this);
    next();
  });

  typesFindQueryMiddleware.forEach((type) => {
    schema.pre(type, excludeInFindQueriesIsDeleted);
  });

  schema.pre('aggregate', excludeInDeletedInAggregateMiddleware);
};

export {
  softDeletePlugin,
};

you can use as global for all schemas

mongoose.plugin(softDeletePlugin);

or for concrete schema

Sign up to request clarification or add additional context in comments.

Comments

1

For Soft delete, you should maintain an active flag column that should only contain values as 0 and 1.

This way, you could analyse whether a record is deleted or not.

While displaying, add another clause for displaying only the records that have flag value 1. And while deleting, just update that flag's value to 0.

This would do the job.

For Example, here user 2 is deleted. with activeFlag as 0.

ID      memberID    userStatus  groupCode  activeFlag
1       user1       1           4455           1
2       user2       1           4220           0
3       user3       2           4220           1

3 Comments

@Sethulakshmi You had a query? I see you deleted a comment.
yeah I had a query...I did as you said set an active flag to 1 and while clicking delete button, i updated the flag value to 0. After that how to view the records that have flag set to 0?
You mean the ones you soft deleted? It's simple. While making a normal find() or Select query, add a condition of activeFlag:0 . It's simple and easy to use. Let me know if you still have a query.
0

Try to use https://www.npmjs.com/package/soft-delete-mongoose-plugin

A simple and friendly soft delete plugin for mongoose.

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.