如何使用Node.js与MongoDB进行软删除

时间:2019-05-09 06:17:00

标签: node.js mongodb

我能够从视图中删除数据,但是同时它会从mongodb中删除,这是不应该发生的。

我尝试过mongoose-soft-delete插件来执行软删除,但是它不起作用

//模式

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模板

<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文件

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

    }

//服务

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});
    }

});
});

现在数据将从视图以及mongodb中删除。

预期结果是仅从视图而不是从mongodb删除数据

2 个答案:

答案 0 :(得分:0)

对于软删除,您应维护一个活动的标志列,该列仅应包含0和1的值。

这样,您可以分析记录是否被删除。

在显示时,添加另一个子句以仅显示具有标志值1的记录。在删除时,只需将该标志的值更新为0。

这可以完成工作。

例如,此处删除用户2。将activeFlag设置为0。

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

答案 1 :(得分:0)

我们可以使用插件,中间件和$ isDeleted文档方法实现软删除

软删除插件代码:

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,
};

您可以将其用作所有架构的全局

mongoose.plugin(softDeletePlugin);

或针对具体架构