mongoose 使用对象 ID 软删除

aka*_*wal 3 soft-delete mongoose node.js

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

小智 7

你不需要任何库,使用中间件和 $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,
};

Run Code Online (Sandbox Code Playgroud)

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


Dom*_*vić 2

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

它提供了新的delete功能。