首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用对象ID的mongoose软删除

使用对象ID的mongoose软删除
EN

Stack Overflow用户
提问于 2017-04-07 19:15:38
回答 4查看 9.4K关注 0票数 3

因此,我尝试使用mongoose-delete插件来软删除mongoDB中的数据,但请求只获得了mongoose对象的对象ID。因此,为了“软删除”数据,我必须首先执行findOne,然后对其使用delete函数。有没有什么插件或函数可以让我只用对象ID就能软删除这些数据?而不是使用两次命中数据库。数据是关键的,因此只需要软删除选项,而不是硬删除。而且我不能使用通用的更新功能,需要一些插件或节点模块来为我做这件事。

EN

回答 4

Stack Overflow用户

发布于 2020-05-25 22:53:59

您不需要任何库,使用中间件和$isDeleted文档方法编写自己很容易

插件代码示例:

代码语言:javascript
运行
复制
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,
};

您可以将其用作全局插件或指定模式的插件

票数 9
EN

Stack Overflow用户

发布于 2017-04-07 19:22:23

您可以使用mongoose-delete:https://github.com/dsanel/mongoose-delete

它提供了新的delete函数。

票数 2
EN

Stack Overflow用户

发布于 2018-12-02 13:32:42

您可以使用Mongoosejs Soft delete。看看GitHub Repository上的代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43276776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档