node.js - 如何使用nodejs对mongodb进行软删除

标签 node.js mongodb

我能够从 View 中删除数据,但同时它也会从 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});
    }

});
});

现在数据将从 View 和 mongodb 中删除。

预期结果是仅从 View 中删除数据,而不是从 mongodb 中删除数据

最佳答案

我们可以通过插件、中间件和$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);

或具体模式

关于node.js - 如何使用nodejs对mongodb进行软删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56053252/

相关文章:

javascript - 在 mongodb 中对多个文档进行分组

mongodb - 使用spring data mongodb删除对象中的数组条目

mongodb - 每小时更新数据库(mongo)的最佳方法?

node.js - 如何在 mongoDB 中创建复合唯一键

node.js - 如何为 Express v4.13 设置 SSL 证书?

javascript - React - 改变一个不受控制的输入

node.js - 如何检测订阅者是否离开 Redis PUB/SUB channel ?

mysql - NodeJS Mysql 停止服务器因错误而崩溃

javascript - 将 cURL 请求转换为 node.js 的请求

sql - 对于社交网站(使用 Ruby on Rails 开发)来说,MongoDB 会是一个好主意吗?